简体   繁体   English

Model 未绑定到 JSON

[英]Model not binding to JSON

It looks like my model is not bingding correctly and the fields are all nulls.看起来我的 model 没有正确绑定,并且字段都是空的。 I have looked online and it seems that none of the solution worked for me.我在网上看过,似乎没有一个解决方案对我有用。 All my properties have setters and getters, the property name of the JSON matches the Model and I am stringifying it.我所有的属性都有设置器和获取器,JSON 的属性名称与 Model 匹配,我正在对其进行字符串化。 I am setting my headers correctly.我正确设置了我的标题。 Perhaps there is something simple I am not setting.也许我没有设置一些简单的东西。 Maybe a missing package?也许缺少 package? Calling something incorrectly?错误地调用某些东西?

On the frontend this is how I am posting my JSON在前端,这就是我发布 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();
    });
});

the content of userData userData 的内容

{"UserId":"4dd9f40e-a9ad-418e-9954-e9459c5db1af","FirstName":"Jack","LastName":"","EmployeeCode":"",
 "PhoneNumber":"","Email":"jthor@stackoverflow.com"}

my controller method我的 controller 方法

 [HttpPost]
 public JsonResult SaveUser(UserModel user)
 {
    UserModel.UpdateUser(user);
    return Json(false);
 }

my Model我的 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>();
    }
}

I've had this problem before and I was able to fix it by adding the [FromBody] attribute.我以前遇到过这个问题,我可以通过添加[FromBody]属性来解决它。

[HttpPost]
 public JsonResult SaveUser([FromBody] UserModel user)
 {
    UserModel.UpdateUser(user);
    return Json(false);
 }

Try changing the Content header to "Content-Type", it works for me.尝试将 Content header 更改为“Content-Type”,它适用于我。

As follows:如下:

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

I figured it out.我想到了。 Instead of manually creating the form using HTML I used the html helper html.beginform and that worked.我没有使用 HTML 手动创建表单,而是使用了 html 助手html.beginform并且有效。 IDK why that worked but it did. IDK 为什么这有效,但确实有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM