Nicholas Murray
Nicholas Murray

Reputation: 13533

Problems posting JSON object array to Asp.Net MVC 2

I am having problems posting a JSON array of objects to an ActionResult in Asp.Net MVC where the list of objects received is always null.

Here is the offending code:

Javascript:

        var lineItems = new Object();
        lineItems.Entrys = new Array()
        var i = 0;
        var currentId = 0;

        $('#pages-table td.PageId').each(function () {
            currentId = $(this).html().toString().trim();
            lineItems.Entrys[i] = new Object({ ID: currentId, POS: i });
            i++;
        });

        $.ajax({
            url: 'UpdatePageOrder',
            data: JSON.stringify(lineItems),
            contentType: 'application/json',
            dataType: 'json',
            traditional: true,
            type: 'POST',
            success: function (result) {
            }
        });

Asp.Net MVC

    public class PageOrder
    {
        public string ID { get; set; }
        public string POS { get; set; }
    }


    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult UpdatePageOrder(List<PageOrder> list)
    {
    var newPageOrderList = list;
    ... list is always null

}

Fiddler TextView:

 {"Entrys":[{"ID":"0","POS":"7"},{"ID":"1","POS":"3"}]}

EDIT *

Downloaded MVC2 Futures and added to OnApplicationStarted (I'm using ninject)

ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());

Upvotes: 1

Views: 1204

Answers (1)

Steve Hobbs
Steve Hobbs

Reputation: 3326

I don't believe MVC 2 has automatic binding support for JSON which would explain your problem.

Phil Haack discusses a solution at the following link which takes you through building a JsonValueProvider to get around this particular problem.

http://haacked.com/archive/2010/04/15/sending-json-to-an-asp-net-mvc-action-method-argument.aspx

Edit: sorry, he doesn't take you through the actual implementation, but talks about it and provides a link to a sample containing the provider towards the end. MVC 3 has this support built-in, so if you can upgrade you would sort this problem straight away.

Upvotes: 2

Related Questions