【发布时间】:2014-07-27 11:12:21
【问题描述】:
我正在使用一个 jQuery 插件,jTable。该插件具有以下加载表格的功能:
$('#PersonTable').jtable('load', { CityId: 2, Name: 'Halil' });
加载函数中的值作为 POST 数据发送。该插件还通过 URL 发送两个查询字符串参数(jtStartIndex、jtPageSize)用于分页。
文档中的示例显示了如何在 ASP.NET MVC 中处理此问题的函数,而不是在 Web API Example 中:
[HttpPost]
public JsonResult StudentListByFiter(string name = "", int cityId = 0, int jtStartIndex = 0, int jtPageSize = 0, string jtSorting = null)
{
try
{
//Get data from database
var studentCount = _repository.StudentRepository.GetStudentCountByFilter(name, cityId);
var students = _repository.StudentRepository.GetStudentsByFilter(name, cityId, jtStartIndex, jtPageSize, jtSorting);
//Return result to jTable
return Json(new { Result = "OK", Records = students, TotalRecordCount = studentCount });
}
catch (Exception ex)
{
return Json(new { Result = "ERROR", Message = ex.Message });
}
}
我的函数目前看起来如何:它工作正常,只是我无法读取 POST 数据(名称参数):
public dynamic ProductsList(string name = "", int jtStartIndex = 0, int jtPageSize = 0 )
{
try
{
int count = db.Products.Count();
var products = from a in db.Products where a.ProductName.Contains(name) select a;
List<Product> prods = products.OrderBy(x => x.ProductID).ToList();
return (new { Result = "OK", Records = prods, TotalRecordCount = count });
}
catch (Exception ex)
{
return (new { Result = "ERROR", Message = ex.Message });
}
}
我的 jTable 加载:(当用户在输入中输入文本时会调用它)
$('#ProductTable').jtable('load', {
name: $('#prodFilter').val()
});
对于如何读取 URL 中的字符串参数和 Web API 函数中的 POST 数据,我将不胜感激。
编辑: 我使用了另一种方法将数据发送到 API。我没有在格式为 JSON 的加载函数中发送它,而是使用 listAction 的函数并通过 URL 发送数据(有关详细信息,请参阅 jTable API 参考):
listAction: function (postData, jtParams) {
return $.Deferred(function ($dfd) {
$.ajax({
url: 'http://localhost:53756/api/Product/ProductsList?jtStartIndex=' + jtParams.jtStartIndex + '&jtPageSize=' + jtParams.jtPageSize + '&name=' + $('#prodFilter').val(),
type: 'POST',
dataType: 'json',
data: postData,
success: function (data) {
$dfd.resolve(data);
},
error: function () {
$dfd.reject();
}
});
});
}
根据过滤结果重新加载表格:
$('#ProductTable').jtable('load');
而不是这个:
$('#ProductTable').jtable('load', {
name: $('#prodFilter').val()
});
【问题讨论】:
-
请求是否命中服务器?
jtStartIndex/jtPageSize参数是否绑定? -
是的,我可以毫无问题地读取函数中的 jtStartIndex / jtPageSize 参数。只是名字我看不懂。
标签: javascript jquery json asp.net-web-api jquery-jtable