MVC 3 AJAX Post,列表填充了对象,但对象属性为空

Shi*_*ion 8 ajax jquery model-binding asp.net-mvc-3

我有以下问题:

在按钮上单击我将一些数据发送到服务器.我的控制器Action看起来像这样:

public ActionResult Accept(List<MyViewModel> entries)
{
    //here entries HAS 2 MyViewModel-Instances in it.
    //The entries are not null, but the values of the instances are!
    //entries[0].ParamA is null
}
Run Code Online (Sandbox Code Playgroud)

MyViewModel的位置如下:

public class MyViewModel
{
    public string ParamA { get; set; }
    public string ParamB { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

而AJAX-Call则是以下内容:

var myEntries = { entries: [{ ParamA: "A", ParamB: "B" }, { ParamA: "C", ParamB: "D" }] };

$.ajax({
    type: 'POST',
    url: url,
    cache: false,
    data: myEntries,
    dataType: 'text' });
Run Code Online (Sandbox Code Playgroud)

我已经尝试过做的事情:

  • 将dataType更改为'json'
  • 使用:传统:真实
  • 尝试了var myEntries = JSON.stringify(...);
  • 尝试了var myEntries = {entries:[JSON.stringify({...}),JSON.stringify({...})]};
  • 与上面相同,但是使用jQuery.param(...,true);
  • 使用IEnumerable或MyViewModel []而不是list.
  • 以上的任何组合

我在这做错了什么?

非常非常感谢您提前帮助我!

编辑

我的(Razor)视图此刻并不有意思,因为它与任何事情无关.我没有使用任何HTML.TextBoxFor(或类似的)方法来填充myEntries-Variable.它实际上是动态填充的(因为有很多条件).为了问题(以及我自己的测试),我对变量进行了硬编码.:)

And*_*rew 12

有了你的答案和使用JSON.stringify方法,它对我有用

var myEntries = { entries: [{ ParamA: "A", ParamB: "B" }, 
                            { ParamA: "C", ParamB: "D" }] };

$.ajax({
        type: 'POST',
        url: '/{controller}/{action}',
        cache: false,
        data: JSON.stringify(myEntries),
        dataType: 'json', 
        contentType: 'application/json; charset=utf-8'
    });
Run Code Online (Sandbox Code Playgroud)


Shi*_*ion 5

我得到了答案!

jQuery有时会令人困惑.

dataType是指定要从服务器获取BACK的内容的参数.contentType是指示您发送给服务器的内容的参数.

所以从上面的例子中,如果你添加:

contentType:'application/json; 字符集= UTF-8' ,

在AJAX调用中.