gpt4 book ai didi

asp.net-mvc-4 - 在asp.net mvc4中将List从 Controller 返回到ajax

转载 作者:行者123 更新时间:2023-12-04 04:35:59 26 4
gpt4 key购买 nike

我试图在 jquery ajax 调用时从 Controller 获取列表。

但它返回一个错误“意外的 token S”。

更新- Controller 代码没问题。它成功地准备了 list 。但是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);
}
});

Controller 中的代码
    [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;
}

}

有什么建议吗?

最佳答案

将其作为 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);
},

关于asp.net-mvc-4 - 在asp.net mvc4中将List<T>从 Controller 返回到ajax,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19750691/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com