1

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

1 Answer 1

2

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.

4
  • @elkdanger - Please see above Commented Jan 28, 2011 at 10:25
  • Ok, and the result? I'm assuming this hasn't fixed your issue. Commented Jan 28, 2011 at 10:34
  • Also I see your parameter names don't match up. The parameter on your action is named 'list' but the JSON packet contains an array with the key 'entrys'. Can you try changing your parameter name to 'entrys' also and observe the results? Commented Jan 28, 2011 at 10:38
  • @elkdanger - Sonic Boom! - that was it - well spotted. Commented Jan 28, 2011 at 10:48

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.