墨菲定律,我一提出这个问题就发现
sample
这让我振作起来。
最后的诀窍是使用jquery解析wcf服务返回的字符串。如果不这样做,datatables脚本就无法理解wcf使用的JSON格式,因为它要么是非标准的,要么是在推动边界。
$(document).ready(function () {
$('#example').dataTable({
"bJQueryUI": true,
"bSort": true,
"bProcessing" : true,
"bServerSide" : true,
"bAutoWidth": true,
"sAjaxSource": "http://10.1.1.7/mvc-jqdatatable/datatabletestservice.svc/gettable",
"fnServerData": function(sSource, aoData, fnCallback) {
$.ajax({
"datatType" : 'json',
"contentType" : 'application/json',
"url" : sSource,
"data" : aoData,
"success" : function(msg) {
var json = $.parseJSON(msg);
fnCallback(json);
}
})
},
});
});
与以下WCF服务一起工作:
public interface IDataTableTestService
{
[OperationContract]
[WebInvoke(ResponseFormat=WebMessageFormat.Json, BodyStyle=WebMessageBodyStyle.WrappedRequest, Method="GET")]
string GetTable(int iDisplayStart,
int iDisplayLength,
string sSearch,
bool bEscapeRegex,
int iColumns,
int iSortingCols,
int iSortCol_0,
string sSortDir_0,
int sEcho,
int webSiteId,
int categoryId);
}
public class DataTableTestService : IDataTableTestService
{
public string GetTable(int iDisplayStart,
int iDisplayLength,
string sSearch,
bool bEscapeRegex,
int iColumns,
int iSortingCols,
int iSortCol_0,
string sSortDir_0,
int sEcho,
int webSiteId,
int categoryId)
{
var result = new List<string[]>() { new string[]{"a", "b", "c"}, new string[]{"d", "e", "f"}};
JavaScriptSerializer serialiser = new JavaScriptSerializer();
return serialiser.Serialize(new { sEcho,
iTotalRecords = 2,
iTotalDisplayRecords = 2,
aaData = result
});
}
}