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());
asked Jan 28, 2011 at 9:59

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.

answered Jan 28, 2011 at 10:03

4 Comments

@elkdanger - Please see above
Ok, and the result? I'm assuming this hasn't fixed your issue.
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?
@elkdanger - Sonic Boom! - that was it - well spotted.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.