MVC 3 AJAX后,名单充满了对象,但对象属性是空的 [英] MVC 3 AJAX Post, List filled with Objects, but Objects Properties are Empty

查看:145
本文介绍了MVC 3 AJAX后,名单充满了对象,但对象属性是空的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下问题:

上的一个按钮,点击我张贴一些数据到服务器。 我的控制器动作看起来是这样的:

On a Button-Click I POST some data to the server. My controller Action looks like this:

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
}

凡MyViewModel看起来是这样的:

Where the MyViewModel looks like this:

public class MyViewModel
{
    public string ParamA { get; set; }
    public string ParamB { get; set; }
}

和AJAX的呼叫是follwing:

And the AJAX-Call is the follwing:

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

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

我已经尝试过的事情:

  • 改变数据类型设置为json的
  • 使用:传统:真正的
  • 在试图变种myEntries = JSON.stringify(...);
  • 在试图变种myEntries = {项:[JSON.stringify({...}),JSON.stringify({...})};
  • 同上,但jQuery.param(...,真);
  • 使用的IEnumerable的[]的MyViewModel代替或列表。
  • 上述
  • 的任意组合
  • Changed dataType to 'json'
  • used: traditional: true
  • tried var myEntries = JSON.stringify(...);
  • tried var myEntries = { entries : [JSON.stringify({ ... }), JSON.stringify({ ... })] };
  • same as above, but with jQuery.param(..., true);
  • Use of IEnumerable or MyViewModel[] instead of list.
  • ANY combination of the above

我在做什么错在这里?

感谢您非常,非常事先对我的帮助!

Thank you very, very much in advance for helping me!

修改

我的(剃刀)查看是不是在这一刻,因为它有无关,与任何有趣。我没有使用任何HTML.TextBoxFor(或similiar)方法,以填补myEntries变量。它实际上是动态填充(因为有很多很多的条件)。 为了这个问题(和我自己的测试)的我硬codeD的变量。 :)

My (Razor)View is not interesting at this moment as it has nothing to do with anything. I am NOT using any of the HTML.TextBoxFor (or similiar) Methods to fill the myEntries-Variable. It is actually filled dynamically (because there are many many conditions). For the sake of the question (and my own testing) i hard-coded the variable. :)

推荐答案

随着你的答案和使用 JSON.stringify 法的工作对我来说

With your answer and the use of JSON.stringify method it works for me

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'
    });

这篇关于MVC 3 AJAX后,名单充满了对象,但对象属性是空的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆