我返回datatable
中的值列表,并且我想在dropdownlist
中填写ajax函数的success
部分。直到返回 dt 为止,我正确地获取了所有值,但之后它进入了错误部分。以下是我尝试过的。
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..!!');
}
});
}
并在后面的代码中:-
[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;
}
}
为什么它总是出现在我不明白的错误
部分?如果我在任何地方出错,请提出建议。
最佳答案
您不能像这样直接从 [WebMethod]
返回 DataTable
。在发送到 cleint 之前,您需要将 DataTable
转换为 JSON
。
更改您的服务器端代码,如下所示。
[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);
}
}
关于javascript - 在 asp.net 中,Ajax 返回数据表总是出现错误部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48982067/