JSON对象未正确发送到我的ASP.NET MVC控制器,缺少属性

时间:2016-02-04 15:30:34

标签: javascript asp.net json asp.net-mvc asp.net-mvc-3

我将JSON objject传递给ASP.NET MVC控制器时出现问题。

JSON以这种方式设置在JS中:

 jsonChildren = '{ "childImproItems" : [{ "Theme":"tralalali"  }, { "Theme":"tralalali"  }]}';
...
  $.ajax({
           url: url,  
            type: 'POST',
            data: JSON.parse(jsonChildren),
            success: function (result) {
              ...  
            },
            error: function (result) {
              ..
            }
        });

在我的控制器内:

public int MyMethod(String typeName, SelectOptionsViewModel id) {
  return 0;
}

有关的模型类如下:

public class SelectOptionsViewModel {
        ...
  public List<ChildImproItemViewModel> childImproItems { get; set; }
}

public class ChildImproItemViewModel {
        ...
  public string Theme { get; set; }
}

调试器正确地将我路由到我的控制器并正确地将JSON解释为SelectOptionsViewModel实例。 它使用2个对象的列表正确设置其childImproItems属性。 但是2个childImproItems对象的Theme属性为null,尽管它们应该在我的示例中设置为虚拟值。 其他属性也是如此。

你们看到我的错误在哪里吗?

提前thx。

编辑: 如果我自己创建JSON对象,则完全相同:

   JSONFormatChildren = {};
    JSONFormatChildren.childImproItems = {};
    JSONFormatChildren.childImproItems[0] = {};
    JSONFormatChildren.childImproItems[0].Theme = 'trouloulou';
    JSONFormatChildren.childImproItems[1] = {};
    JSONFormatChildren.childImproItems[1].Theme = 'trouloulou';

然后是ajax:

 $.ajax({
            url: url,  //We can't pass the selectId directly as C# does not know about JS variables
            type: 'POST',
            data: JSONFormatChildren,
....
}

再次,使用corract数量的元素(2)正确创建列表,但所有元素Theme property = null而不是trouloulou ......

编辑2: 如果我使用这个JSON:

 jsonChildren = '{"Theme":"tralalali"}';

这个方法:

 public int test2(String typeName, ChildImproItemViewModel id) 
    {
        return 0;
    }

一切正常

如果我使用这个JSON:

 jsonChildren = '[{"Theme":"tralalali"},{"Theme":"tralalali"}]'; 

这个方法:

   public int test2(String typeName, List<ChildImproItemViewModel> id) 
    {
        return 0;
    }

它不起作用:调用方法时id = null

1 个答案:

答案 0 :(得分:0)

你需要正确地将内容类型指定为json,因为jquery中的默认值是form-url-encoded。另外,我认为JSON.Parse函数是不必要的,可以使用/不使用它。

编辑:我刚刚注意到您正在尝试手动创建JSON字符串。这是一个坏主意,只需创建一个Javascript对象,然后使用JSON.stringify()。否则,很容易搞砸JSON字符串语法。如果您支持旧浏览器,则可能需要包含json2.js库

var     jsonChildren = { "childImproItems" 
: [{ "Theme":"tralalali"  }, { "Theme":"tralalali"  }]};
    ...

  $.ajax({
           url: url,  
            type: 'POST',
            data: JSON.stringify(jsonChildren),
            contentType: 'application/json',
            success: function (result) {
              ...  
            },
            error: function (result) {
              ..
            }
        });