返回列表<t>从控制器返回到asp.net mvc4中的ajax </t>

时间:2013-11-03 07:14:16

标签: asp.net-mvc-4

我试图在jquery ajax调用时从控制器获取一个列表。

但它返回错误'意外的令牌S'。

UPDATE-控制器代码正常。它成功地准备了清单。但是ajax显示了这个错误。

jquery 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);
}
});

控制器中的代码

    [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;
    }

}

有什么建议吗?

2 个答案:

答案 0 :(得分: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);
},

答案 1 :(得分:0)

您的问题如下:

请阅读有关此link

的信息

您发送的数据看起来不像有效的json数据