[英]Model not binding to JSON
看起来我的 model 没有正确绑定,并且字段都是空的。 我在网上看过,似乎没有一个解决方案对我有用。 我所有的属性都有设置器和获取器,JSON 的属性名称与 Model 匹配,我正在对其进行字符串化。 我正确设置了我的标题。 也许我没有设置一些简单的东西。 也许缺少 package? 错误地调用某些东西?
在前端,这就是我发布 JSON 的方式
fetch("/Admin/SaveUser", {
method: "Post",
headers: {
"Content": "application/json",
'Accept': 'application/json;charset=utf-8'
},
body: JSON.stringify(userData)
}).then(response => {
response.json().then(result => {
UpdateDisplay();
});
});
userData 的内容
{"UserId":"4dd9f40e-a9ad-418e-9954-e9459c5db1af","FirstName":"Jack","LastName":"","EmployeeCode":"",
"PhoneNumber":"","Email":"jthor@stackoverflow.com"}
我的 controller 方法
[HttpPost]
public JsonResult SaveUser(UserModel user)
{
UserModel.UpdateUser(user);
return Json(false);
}
我的 Model
public class UserModel
{
public Guid UserId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string PhoneNumber { get; set; }
public string EmployeeCode { get; set; }
public List<string> UserRoleIds { get; set; }
public List<string> UserRoleNames { get; set; }
public List<SelectListItem> Roles { get; set; }
public UserModel()
{
UserRoleIds = new List<string>();
UserRoleNames = new List<string>();
Roles = new List<SelectListItem>();
}
}
我以前遇到过这个问题,我可以通过添加[FromBody]
属性来解决它。
[HttpPost]
public JsonResult SaveUser([FromBody] UserModel user)
{
UserModel.UpdateUser(user);
return Json(false);
}
尝试将 Content header 更改为“Content-Type”,它适用于我。
如下:
fetch("/Admin/SaveUser", {
method: "Post",
headers: {
"Content-Type": "application/json",
'Accept': 'application/json;charset=utf-8'
},
body: JSON.stringify(userData)
}).then(response => {
response.json().then(result => {
UpdateDisplay();
});
});
我想到了。 我没有使用 HTML 手动创建表单,而是使用了 html 助手html.beginform
并且有效。 IDK 为什么这有效,但确实有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.