Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
189 views
in Technique[技术] by (71.8m points)

c# - Ajax post to ASP.net MVC controller - object properties are null

I've got an ajax post being constructed like 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 an MVC controller:

[HttpPost]
public JsonResult MyAction(MyClass[] items)
{

}

MyClass is just a simple representation of the data:

public class MyClass {
    public string Name {get; set; }
    public string Id {get; set; }
}

When the javascript makes the post request, the controller action does indeed receive 2 items, however the properties (id, name) in these items are null.

Checking the request in fiddler, the body looks like this:

Name                 | Value
items[0][Name]       | Name 1
items[0][Id]         | a
items[1][Name]       | Name 2
items[1][Id]         | b

Have I missed something?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Have I missed something?

Yes, take a look at the following article to understand the correct wire format that the default model binder expects for binding collections. In other words, for this to work, instead of:

items[0][Name]       | Name 1
items[0][Id]         | a
items[1][Name]       | Name 2
items[1][Id]         | b

your payload should have looked like this:

items[0].Name       | Name 1
items[0].Id         | a
items[1].Name       | Name 2
items[1].Id         | b

Unfortunately with jQuery it can be quite frustrating to achieve this payload. For this reason I would recommend that you use a JSON payload if you want to send complex objects/arrays to your server with AJAX:

$.ajax({
    type: 'POST',
    url: '/myurl/myAction',
    data: JSON.stringify({ items: myData }),
    contentType: 'application/json',
    error: function (err) {
        alert("error - " + err);
    }
});

Things to notice:

  • data: JSON.stringify({ items: myData }) instead of data: { items: myData }
  • Added contentType: 'application/json'
  • Gotten rid of dataType: 'json'

Now your payload looks like this:

{"items":[{"id":"a","name":"Name 1"},{"id":"b","name":"Name 2"}]}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...