【发布时间】:2019-02-22 10:02:29
【问题描述】:
我需要将 DataTable 从 c#(WebMethod) 返回到 Ajax。 我正在向 WebMethod 发送“值”。值被接收并用作下面代码中的过程的参数 (getObj.getValuesTableAdapter(Value);)。
然后过程返回 datatable(dtObj) 并且 ajax 应该在“成功”部分接收它。 我需要这些代码的帮助。我尝试了所有方法,但都失败了。
我不能像这样直接从 [WebMethod] 返回 DataTable。在以某种方式发送到客户端之前,我需要将 DataTable 转换为 JSON。
这是我的 C# 代码:
[WebMethod(EnableSession = true)]
public static DataTable GetObject(int Value)
{
LogicTableAdapters.getValuesTableAdapter getObj = new LogicTableAdapters.getValuesTableAdapter();
DataTable getObj = getObj.getValuesTableAdapter(Value);
DataTable dtObj = new DataTable();
dtObj.Columns.AddRange(new DataColumn[4]{
new DataColumn("ObjectID", typeof(string)),
new DataColumn("ObjectName", typeof(string)),
new DataColumn("ObjectValue", typeof(string)),
new DataColumn("ParentID", typeof(int)),
});
foreach (DataRow dr in getObj.Rows)
{
dtCh.Rows.Add(dr["ObjectID"].ToString(), dr["ObjectName"] == DBNull.Value ? null : dr["ObjectValue"].ToString(), dr["ParentID"].ToString());
}
return dtObj;
}
这是我的 ajax:
$(document).on('click', ".Btn", function () {
header = $(this).closest('tr').find('.ColumnID').text()
console.log(Value);
$.ajax({
type: "POST",
url: "MyAdmin.aspx/GetObject",
data: JSON.stringify({ 'Value': Value }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
//code that should receive datatable to be displayed
},
error: function () {
}
});
});
提前致谢!
【问题讨论】: