2013-11-03 39 views
1

我試圖從jquery ajax調用中獲取控制器列表。返回列表<T>從控制器到asp.net中的ajax mvc4

但它返回一個錯誤'Unexpected token S'。

更新 - 控制器代碼是好的。它成功地準備了清單。但阿賈克斯顯示這個錯誤。

jquery的在控制器

[HttpPost] 
    public List<Thana> GetThanas(int id) 
    { 
     return Thana.GetThanaList(id); 
    } 

更新 - 型號代碼

public class Thana 
{ 

    public String ThanaId { get; set; } 
    public String ThanaName { get; set; } 

    public Thana() { } 


    public static List<Thana> GetThanaList(Int32 districtId) 
    { 
     List<Thana> thanaList = new List<Thana>(); 


     String ConnectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString; 
     using (SqlConnection Connection = new SqlConnection(ConnectionString)) 
     { 
      using (SqlCommand cmd = new SqlCommand("Select ThanaId,ThanaName From tblThanas where ThanaId<>0 And DistrictId=" + districtId + " or DistrictId=0 order By DisplayOrder ASC, ThanaName ASC ", Connection)) 
      { 
       Connection.Open(); 
       SqlDataReader Reader = cmd.ExecuteReader(CommandBehavior.CloseConnection); 
       while (Reader.Read()) 
       { 
        Thana thana = new Thana(); 
        thana.ThanaId = Reader["ThanaId"].ToString(); 
        thana.ThanaName = Reader["ThanaName"].ToString(); 
        thanaList.Add(thana); 
       } 
       if (!Reader.IsClosed) 
       { 
        Reader.Close(); 
       } 
      } 
     } 



     return thanaList; 
    } 

} 

任何建議AJAX代碼 -

var urlData = '@Url.Action("GetThanas", "AgentKycEntry")'; 
$.ajax({ 
type: "POST", 
url: urlData, 
contentType: "application/json; charset=utf-8", 
data: "{'id':'" + selectedVal + "'}", 
dataType: "json", 
success: function (result) { 
//tasks with restul 
}, 
error: function (request, status, error) { 
alert("Request: " + request + " Status: " + status + " Error: " + error); 
} 
}); 

碼?

+0

你從哪裏得到這個錯誤?在控制器? – MRB

+0

在ajax獲取列表時。控制器沒問題。 –

回答

2

返回它作爲JSON,試試這個。

public JsonResult GetThanas(int id) 
    { 
     var list = Thana.GetThanaList(id); 
     return Json(list, JsonRequestBehavior.AllowGet); 
    } 

編輯:

success: function (result) { 
//tasks with restul 
    alert(result[0].ThanaName); 
}, 
+0

我試過了。 '意外的令牌S'錯誤消失了。但我沒有得到數據列表。結果= [對象對象],[對象對象],..... –

+0

我可以看到'GetThanaList'嗎? – WannaCSharp

+0

我編輯了我的答案。檢查它, – WannaCSharp

0

你的問題是這樣的:

請閱讀此link

你發送的數據犯規貌似有效的JSON數據

相關問題