user480184
user480184

Reputation:

MVC parameter from JQuery null

I am trying to implement sorting on a custom grid I am working on and having an issue with jQuery to MVC parameter binding.

I have a Jquery request like the one shown below

// Javascript

var dataobj =
            {
                test: 3,
                sortInfo: self.sortInfo,
                pagingInfo: {
                    TotalItems: 34, //headercontainer.attr("data-pagingInfo-TotalItems"),
                    ItemsPerPage: headercontainer.attr("data-pagingInfo-ItemsPerPage"),
                    CurrentPage: headercontainer.attr("data-pagingInfo-CurrentPage")
                }
            };

 $.ajax({
            url: self.viewModel.GenericGridHeaderModel.SortingCallbackUrl,
            type: 'POST',
            data: dataobj,
            dataType: "json",
            success: function (html) {...}
         });

// C#
public PartialViewResult GenericGridSort(int test, SortInfo sortInfo, PagingInfo pagingInfo){
...
}

At the moment I have non null values in sortInfo object in Javascript and I see that the values are posted correctly however inside the action method the values are not getting bound correctly. All I see is default values for the sortInfo and pagingInfo parameters. In fact the test parameter is getting the value 3 correctly.

For clarity here is my sortInfo model

public enum SortDirection
{
    None = 0,
    Ascending = 1,
    Descending = 2
}

public class SortInfo
{
    public int FieldIndex { get; set; }
    public string FeildName { get; set; }
    public SortDirection SortDirection { get; set; }
}

Can anyone tell me what am I missing here ?

Thanks all !

Upvotes: 0

Views: 731

Answers (2)

Roger Barreto
Roger Barreto

Reputation: 2284

Wow, as soon as I know that will not work. When you attempt to pass inner objects in your ajax data you must reference the inner objects properties strictly in the root of data ("innerobject.property": value)

Example:

var dataobj =
        {
            test: 3,
            "sortInfo.property1": self.sortInfo.property1,
            /* other properties */

            "pagingInfo.TotalItems": 34, 
            //headercontainer.attr("data-pagingInfo-TotalItems"),
            "pagingInfo.ItemsPerPage": headercontainer.attr("data-pagingInfo-ItemsPerPage"),
            "pagingInfo.CurrentPage": headercontainer.attr("data-pagingInfo-CurrentPage")

        };

Upvotes: 0

Andy T
Andy T

Reputation: 9881

I believe that you are not encoding the JSON payload.

You should be using either:

data: $.toJSON(dataobj),

or

data: JSON.stringify(dataobj),

Also, for contentType use:

contentType: 'application/json; charset=utf-8',

Here is more information on POSTing JSON payload to MVC

Also, in the dataType option you specify the type of the return value, in your case, it looks like the action method will be returning HTML, but you are specifying JSON.

Upvotes: 1

Related Questions