0

I am using a jQuery plugin, jTable. The plugin has the following function to load the table:

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

The values in the load function is send as POST data. The plugin also sends two query string parameters (jtStartIndex, jtPageSize) through the URL for paging the table.

An example in the documentation shows a function on how to handle this in ASP.NET MVC but not in 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 });
    }
}

How my function currently looks: It works fine except that I can't manage to read the POST data (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: (This get called when the user enters text in a input)

$('#ProductTable').jtable('load', {
    name: $('#prodFilter').val()
});

I would appreciate any help with how to read both the string parameters in the URL and the POST data in a Web API function.


EDIT: I used an alternative way to send the data to the API. Instead of sending it in the load function formatted as JSON I used a function for the listAction and sent the data through the URL (See jTable API reference for details):

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

To reload the table based on your filtered results:

$('#ProductTable').jtable('load');

Instead of this:

$('#ProductTable').jtable('load', {
    name: $('#prodFilter').val()
});
  • Is the request hitting the server? Are the `jtStartIndex` / `jtPageSize` parameters bound? – James Jul 27 '14 at 11:21
  • Yes, I can read both the jtStartIndex / jtPageSize parameters in my function without any issues. It is only the name that I can't read. – user2148965 Jul 27 '14 at 11:25

1 Answers1

0

Try applying the [FromBody] attribute to the name parameter

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

The default binder in Web API will look in the URI for simple types like string, specifying the FromBody attribute will force it to look in the body.

James
  • 80,725
  • 18
  • 167
  • 237
  • I just added the [FromBody] to the name parameter but now I get: XMLHttpRequest cannot load ... No 'Access-Control-Allow-Origin' header is present... in the console. I got this problem earlier for all calls but managed to solve it with this answer: [link](http://stackoverflow.com/questions/6290053/setting-access-control-allow-origin-in-asp-net-mvc-simplest-possible-method). Thanks for your help James – user2148965 Jul 27 '14 at 11:40
  • @user2148965 that's a separate issue, that means you are posting to a different domain. If `[FromBody]` resolved your issue then you should mark this as the answer for other users. – James Jul 28 '14 at 07:58
  • My apologies if I was unclear. I only get the "No 'Access-Control-Allow-Origin' header is present" problem when I add the [FromBody] before my name parameter. If I remove it, it works 100% with the code I added in my original question. I would like to know why this creates a problem though. – user2148965 Jul 28 '14 at 16:27
  • @user2148965 can't see why that attribute would cause this, that error is usually related to making AJAX calls to different domains – James Jul 31 '14 at 21:59