c# - Ajax post to ASP.net MVC controller - object properties are null -
i've got ajax post being constructed this:
var mydata = [ { id: "a", name: "name 1" }, { id: "b", name: "name 2" } ]; $.ajax({ type: 'post', url: '/myurl/myaction', data: { items: mydata }, datatype: 'json', error: function (err) { alert("error - " + err); } });
and mvc controller:
[httppost] public jsonresult myaction(myclass[] items) { }
myclass
simple representation of data:
public class myclass { public string name {get; set; } public string id {get; set; } }
when javascript makes post request, controller action indeed receive 2 items, properties (id, name) in these items null.
checking request in fiddler, body looks this:
name | value items[0][name] | name 1 items[0][id] | items[1][name] | name 2 items[1][id] | b
have missed something?
have missed something?
yes, take @ following article understand correct wire format default model binder expects binding collections. in other words, work, instead of:
items[0][name] | name 1 items[0][id] | items[1][name] | name 2 items[1][id] | b
your payload should have looked this:
items[0].name | name 1 items[0].id | items[1].name | name 2 items[1].id | b
unfortunately jquery can quite frustrating achieve payload. reason recommend use json payload if want send complex objects/arrays server ajax:
$.ajax({ type: 'post', url: '/myurl/myaction', data: json.stringify({ items: mydata }), contenttype: 'application/json', error: function (err) { alert("error - " + err); } });
things notice:
data: json.stringify({ items: mydata })
instead ofdata: { items: mydata }
- added
contenttype: 'application/json'
- gotten rid of
datatype: 'json'
now payload looks this:
{"items":[{"id":"a","name":"name 1"},{"id":"b","name":"name 2"}]}
Comments
Post a Comment