为什么 postify 可以工作而 stringify 不行?
在服务器端,我有以下类
public class EditorContext
{
public Module Module { get; set; }
public Holder Holder { get; set; }
}
public class Module
{
public string CodeName { get; set; }
public string Content { get; set; }
}
public class Holder
{
public int Id { get; set; }
public int Type { get; set; }
}
public class EditorController : Controller
{
[HttpPost]
public ActionResult AddModule(EditorContext context)
{
return Json(new { });
}
}
从客户端发送这样的请求
var data =
{
Module:
{
CodeName: 1,
Content: 2
},
Holder:
{
Type: 3,
Id: 4
}
};
$.ajax({
type: "POST",
url: 'Editor/AddModule',
data: JSON.stringify(data),
async: false,
success: function () {
},
error: function (xhr, status, error) {
throw new Error();
}
});
1 - Fiddler 显示他发送了 {"Module":{"CodeName":1,"Content":2},"Holder":{"输入":3,"Id":4}},但在服务器Request.Form = %7b%22Module%22%3a%7b%22CodeName%22%3a1%2c%22Content%22%3a2%7d%2c%22Holder%22%3a%7b%22Type%22%3a3%2c%22Id%22%3a4 %7d%7d,为什么?
2 - 如果我使用“postify”而不是“JSON.stringify(data)”,就像 此处,因此 EditorController.AddModule 已填充 EditorContext。此 postify 将数据更改为“Model.CodeName=1&Model.Content=2&Holder.Type=3&Holder.Id=4”。那么,为什么默认绑定器会自动填充 EditorContext,而在 (1) 中却不会呢?
谢谢
In server side I have following class
public class EditorContext
{
public Module Module { get; set; }
public Holder Holder { get; set; }
}
public class Module
{
public string CodeName { get; set; }
public string Content { get; set; }
}
public class Holder
{
public int Id { get; set; }
public int Type { get; set; }
}
public class EditorController : Controller
{
[HttpPost]
public ActionResult AddModule(EditorContext context)
{
return Json(new { });
}
}
From the client I send request like this
var data =
{
Module:
{
CodeName: 1,
Content: 2
},
Holder:
{
Type: 3,
Id: 4
}
};
$.ajax({
type: "POST",
url: 'Editor/AddModule',
data: JSON.stringify(data),
async: false,
success: function () {
},
error: function (xhr, status, error) {
throw new Error();
}
});
1 - Fiddler shows that he sent {"Module":{"CodeName":1,"Content":2},"Holder":{"Type":3,"Id":4}}, but in server Request.Form = %7b%22Module%22%3a%7b%22CodeName%22%3a1%2c%22Content%22%3a2%7d%2c%22Holder%22%3a%7b%22Type%22%3a3%2c%22Id%22%3a4%7d%7d, WHY?
2 - If instead of "JSON.stringify(data)" I use "postify" like in here, so EditorController.AddModule gets already filled EditorContext. This postify change the data to "Model.CodeName=1&Model.Content=2&Holder.Type=3&Holder.Id=4". So, why in this way EditorContext is filled automatically by default binder and in (1) it doesn't?
Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要告诉绑定器您的数据是 JSON,否则它不知道应该这样解析它。将正确的内容类型标头添加到您的请求中:
You need to tell the binder that your data is JSON, otherwise it has no idea it should be parsing it as such. Add the correct content type header to your request: