以下是我的解决方案。可能有更简单的方法可以做到这一点,但我在下面设置 dataTables 的方式似乎是向 ASP.NET WebMethod 发送和接收 JSON 的最可重用方式。请发布其他对您有用的方法。希望有人会用一种不那么古怪的方式来做“d”的事情。
var $table = $('#TableId');
var url = 'page.aspx/WebMethodName';
var extraData = {
something: 'value1',
somethingElse: 'value2'
};
事件处理程序处理从服务器接收数据。我将 d 属性中的所有内容移动到对象的根目录中。
$table.on('xhr.dt', function (e, settings, json)
{
/// <summary>
/// Fix for asp.net WebMethod compatibility.
/// If json has a d property, then response came from a WebMethod.
/// DataTables needs the contents of the d property to be in the root.
/// </summary>
/// <param name="e">The jQuery event object.</param>
/// <param name="settings">The jquery.DataTables settings object.</param>
/// <param name="json">The data returned from the server.</param>
if(json.d)
{
var data = json.d;
// Clear out json.d to free up memory
json.d = undefined;
$.extend(json, data);
}
// Note no return - we have to manipulate the data directly in the JSON object.
// WHY, OH WHY, CAN'T WE JUST RETURN?
}
);
数据表初始化。我序列化数据以尽可能晚地发送到服务器,以便给自己充足的机会添加到请求中。
$table.DataTable({
ajax: {
{
url: url,
type: 'POST',
contentType: 'application/json',
processData: false, // important so the raw data makes it to the beforeSend handler
beforeSend:function( jqXHR, settings )
{
/// <summary>
/// Converts to json for transmission and adds any extra data desired.
/// </summary>
/// <param name="jqXHR">The jqXHR object.</param>
/// <param name="settings">The settings object.</param>
/// <param name="data">The data that will be sent to the server.</param>
var data = settings.data;
// I postponed the serialization as long as possible, so this is the
// last chance to attach extra data to send along
data.extraData = extraData;
settings.data = JSON.stringify({ WebMethodParameterName: data });
}
}
}
});
在服务器端,我创建了类来对 dataTables 发送并要求作为响应的结构进行建模。 T 是每行数据的类型。 DataTablesResponse 有一个构造函数重载,它接受 request.draw 值并将其粘贴在响应中,所以我不必记住。
[WebMethod]
public static DataTablesResponse<T> WebMethodName(DataTablesRequest request)
{
var response = new DataTablesResponse<T>(request);
// Do something to get my data
List<T> results = GetMyData();
response.data = results;
return response;
}
作为旁注,我试图将它发布到 dataTables.net 论坛,但由于某种原因我无法让它通过草稿......所以它会放在这里。