2

I have a json object like this:

var itemData = {
   "translations":[
      {
         "value":"Byron",
         "languageId":1             
      },
      {
         "value":"hgfdfghds",
         "languageId":3
      }
   ],
   "itemId":204,
   "itemCategoryId":44
};

And I POST it using jQuery like this:

$.ajax({
    url: "items/update",
    dataType: "json",
    type: "POST",
    data: itemData,
});

When the call arrives at my ASP.NET MVC4 controller action, the non-list properties are assigned. However, the translations array only has two empty objects (instantiated, but with null/default property values). Here is my controller action method and my models:

public JsonResult Update(UpdateItemModel model)
{
    if(model.Translations[0].Value!="Byron")
    {
        throw new Exception("That translation's value should have been populated with 'Byron'.");
    }
    return Json("ok");
}

public class UpdateItemModel
{
    public List<TranslationModel> Translations { get; set; }
    public int ItemId { get; set; }
    public int ItemCategoryId { get; set; }
}

public class TranslationModel
{
    public string Value { get; set; }
    public int LanguageId { get; set; }
}

If I look at Request.Form in the immediate window, I can see that the translations "array" is encoded for some reason (maybe that's correct, not sure). If I try Request.Form["translations"] I get null. Here's an example of the raw form data that I'm seeing:

{translations%5b0%5d%5bvalue%5d=Byron&translations%5b0%5d%5blanguageId%5d=1&translations%5b1%5d%5bvalue%5d=hgfdfghds&translations%5b1%5d%5blanguageId%5d=3&itemId=204&itemCategoryId=44}

Not sure if my problem has anything to do with the "encoding" of the json at the beginning of that string. I looked at it in Fiddler and saw the same thing, so I can't blame ASP.NET for tampering.

What could be the problem here?

4

3 回答 3

3

您应该指定内容类型 (json) 并使用JSON.stringify对其进行字符串化

$.ajax({
    url: "items/update",
    dataType: "json",
    contentType: "application/json; charset=utf-8;",
    type: "POST",
    data: itemData,
    data: JSON.stringify(itemData),
});

另一件事是使用添加JsonValueProviderFactory

ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());

Application_Start方法中Global.asax

这篇文章可能会对你有所帮助。

于 2013-07-16T14:16:43.663 回答
1

当您为 Ajax 调用传递数据时,最好指定内容并对数据进行字符串化:

$.ajax({
   /*More stuff*/
   data: JSON.stringify(itemData),
   contentType: 'application/json',
   dataType: "json",
   type: "POST"
});

然后值提供者和默认的 ModelBinder 将完成这项工作。

于 2013-07-16T14:19:53.177 回答
0

我可以看到 json 对象属性与 .net 属性不匹配,在 json 中,.net 中的“值”“值”大小写不同。尝试制作案例以推进 .net 模型

于 2013-07-16T14:07:09.753 回答