Web API字符串参数和POST值

Web API string parameters and POST values

本文关键字:POST 参数 API 字符串 Web      更新时间:2023-09-26

我使用jQuery插件,jTable。该插件有以下函数来加载表:

$('#PersonTable').jtable('load', { CityId: 2, Name: 'Halil' });

load函数中的值作为POST数据发送。该插件还通过URL发送两个查询字符串参数(jtStartIndex, jtPageSize)用于分页表。

文档中的一个示例展示了如何在ASP中处理此问题的函数。. NET MVC但不支持Web API示例:

[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数据(name param):

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 });
    }
}

My jTable load:(当用户在input中输入文本时调用)

$('#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()
});

尝试将[FromBody]属性应用于name参数

public dynamic GetProductList([FromBody]string name = "", int jtStartIndex = 0, jtPageSize = 0)
{
    ...
}

Web API中的默认绑定器将在URI中查找简单类型,如字符串,指定FromBody属性将强制它在body中查找。