[英]Ajax returning datatable always going in error part in asp.net
I return list of values in a datatable
and that I want to fill in success
part of ajax function in dropdownlist
.我在一个返回值的列表
datatable
和我要填写的success
在AJAX功能的一部分dropdownlist
。 Till return dt
I get all the values properly but after that it goes in error
part.直到返回
dt
我才能正确获取所有值,但之后它进入error
部分。 Below is what I tried.以下是我尝试过的。
Ajax function Ajax 函数
function getMZONEWithState(evt) {
var ddlState = $('#ContentPlaceHolder1_ddlState').val();
var ddlMaintenanceZone = $("#ddlMaintenanceZone");
ddlMaintenanceZone.empty().append('<option selected="selected" value="0" disabled = "disabled">State Loading...</option>');
$.ajax({
type: "POST",
url: "Dashboard.aspx/GetMaintZone",
data: JSON.stringify({ ddlState: ddlState }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
},
error: function (response) {
alert('Something went wrong..!!');
}
});
}
And in code behind:-在后面的代码中:-
[WebMethod]
public static DataTable GetMaintZone(string ddlState)
{
DataTable dt = new DataTable();
try
{
CommonDB ObjCommon = new CommonDB();
dt = ObjCommon.GetMZONE(ddlState);
return dt;
}
catch (Exception)
{
throw;
}
}
Why it always goes in error
part I don't understand ??为什么它总是
error
我不明白? Please suggest If I am going wrong anywhere.如果我在任何地方出错,请提出建议。
You can't return DataTable
directly from your [WebMethod]
like this.你不能像这样直接从你的
[WebMethod]
返回DataTable
。 You need to convert your DataTable
to JSON
before sending to cleint.在发送到客户端之前,您需要将
DataTable
转换为JSON
。
Change your server side code like following.更改您的服务器端代码,如下所示。
[WebMethod]
public static string GetMaintZone(string ddlState)
{
DataTable dt = new DataTable();
try
{
CommonDB ObjCommon = new CommonDB();
dt = ObjCommon.GetMZONE(ddlState);
return DataTableToJSON(dt);
}
catch (Exception)
{
throw;
}
}
public static string DataTableToJSON(DataTable table)
{
JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
List<Dictionary<string, object>> parentRow = new List<Dictionary<string, object>>();
Dictionary<string, object> childRow;
foreach (DataRow row in table.Rows)
{
childRow = new Dictionary<string, object>();
foreach (DataColumn col in table.Columns)
{
childRow.Add(col.ColumnName, row[col]);
}
parentRow.Add(childRow);
}
return jsSerializer.Serialize(parentRow);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.