2017-10-11 45 views
1

我試圖從ASP.Net中的AJAX與Razor運行此方法。我沒有任何可見的錯誤,但每次嘗試運行時都會發送給我。我有這樣的方法完美運行。但我想我錯過了一些東西。在System.Data.dll中發生SqlException,但沒有在用戶代碼中處理

enter image description here

這是我的C#方法

[WebMethod] 
public JsonResult GetDeparments() 
{ 
    string cs = "Data Source=DMX87025;Initial Catalog=DB_PCC;Integrated Security=True"; 
    string sql = "SELECT * FROM[DB_PCC].[dbo].[Departments]"; 
    List<Departments> departaments = new List<Departments>(); 

    using (SqlConnection con = new SqlConnection(cs)) 
    { 
     SqlCommand cmd = new SqlCommand(sql , con); 
     cmd.CommandType = CommandType.StoredProcedure; 
     con.Open(); 
     SqlDataReader rdr = cmd.ExecuteReader(); //unhandled expection here 
     while (rdr.Read()) 
     { 
      Departments dep = new Departments(); 
      dep.Id = Convert.ToInt32(rdr["Id"]); 
      dep.Code = rdr["Code"].ToString(); 
      dep.Description = rdr["Description"].ToString(); 
      departaments.Add(dep); 
     } 
    } 

    JavaScriptSerializer js = new JavaScriptSerializer(); 

    return Json(new { success = true, message = (js.Serialize(departaments)) }, 
     JsonRequestBehavior.AllowGet); 
} 
+3

您的選擇命令不是StoredProcedure。刪除設置CommandType的行 – Steve

+0

最重要的是,將'use'應用於所有其他事物,而不僅僅是'SqlConnection',刪除在asp.net mvc中不需要的[WebMethod],並將'departments'直接地,沒有使用手動'JavaScriptSerializer'(你覺得你是序列化只是JSON響應的一部分嗎?)。 – GSerg

回答

4

當你要執行一個存儲過程,當你的命令,你不應該設定一個純文本SQL命令可以使用CommandType.StoredProcedure此屬性是因爲缺省值適用於命令文本

順便說一句,雖然它不是致命錯誤,但最好使用圍繞像SqlCommand和SqlDataReade這樣的可丟棄對象的using語句r

using (SqlConnection con = new SqlConnection(cs)) 
using (SqlCommand cmd = new SqlCommand(sql, con)) 
{ 
    // cmd.CommandType = CommandType.StoredProcedure; 
    ... 
    using(SqlDataReader rdr = cmd.ExecuteReader()) 
    { 
     .... 
    } 

} 
相關問題