C# MVC Controller 错误地解析来自 POST 的 JSON

标签 c# json asp.net-mvc asp.net-core reflection

我正在尝试使网站管理员可以修改网站上的下拉列表。下拉菜单上的选项与关联数据一起存储为 IDropDownEntity,例如JobPriority 有字符串 Name 和字符串 PriorityColor,Branch 有字符串 Name 和 AddressValueObject Address,等等。 View 上的表单工作正常,但是当我将其作为 JSON 发布到 Controller 时,关联的数据值未解析/解析为 null。

我采用 IDropDownEntity 并使用反射和自定义属性来确定哪些属性可供用户编辑,并将结果放入 DropDownEditViewModel 中,如下所示:

public class DropDownEditViewModel
{
    //constructor()
    public int Id { get; set; }
    public string Name { get; set; }

    public List<DDLEntityEditableProperty> EditableProperties { get; set; } = new();
}

public class DDLEntityEditableProperty
{
    //constructor()
    public string Name { get; set; }
    public object? Value { get; set; }
}

在我看来,我有 Name 和 EditableProperties 的输入,以及将 JSON 发送到采用 DropDownEditViewModel 的 Controller 操作的 JQuery,但在 Controller 操作上,值始终为 null。

//javascript that generates JSON like so in a "var formData":
"Id": "1",
  "Name": "Home Office",
  "ExtraFields": [
    {
      "Name": "PhoneNumber",
      "Value": "111-555-0000",
    },
    {
      "Name": "Address",
      "Value": {
        "Address1": "404 Parse Street",
        "Locality": "Notfound",
        "PostCode": "00404"
      }
    }
  ]
}

//posts to controller using jQuery:
$.post("/DropDowns/EditGenericDropDownEntity", formData, function (result, status) {
    ShowNotification(result.success, result.message);
});

发送到 Controller 操作

[HttpPost]
public async Task<IActionResult> EditGenericDropDownEntity(DropDownEditViewModel model)
{
    //model's "Value" is always null
    if (!ModelState.IsValid) return Json(new {success = false, text = ModelState.GetError()});
    else return Ok();
}

我尝试将列表更改为字典 但遇到了相同的问题(键很好,值为 null)。我还尝试将 json 作为字符串发送到 Controller 以使用 Newtonsoft 进行解析,但也无法使其工作。我还可以采取任何其他步骤,或者反射不是此用例的一个选项吗?

最佳答案

您正在使用表单数据内容类型(默认情况下),但它不能包含任何嵌套对象,它应该是一个字典之类。尝试使用 json 内容类型,您需要完整形式的 jquery 请求

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

    success: function (result) {
       
    },
    error: function (jqXHR, textStatus, errorThrown) {
        console.log(jqXHR, textStatus, errorThrown);
    }
});

并将 [FromBody] 添加到操作

public async Task<IActionResult> EditGenericDropDownEntity([FromBody] DropDownEditViewModel model)

关于C# MVC Controller 错误地解析来自 POST 的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76491647/

相关文章:

asp.net-mvc - MVC ajax json 发布到 Controller 操作方法

c# - 在 winforms 中显示数据库中带有名称的图片?

c# - 如何在不在本地计算机上安装消息队列的情况下从远程计算机读取 MSMQ 消息?

c# - NHibernate/事件记录 : How to set foreign key without getting entire object?

c# - 将 DataGrid 的 FontWeight 属性绑定(bind)到值转换器

java - 使用 Java 将 JSON 数据推送到文件

javascript - Spark 2.0.0 - JSON 格式错误的输出

jquery - ASP.NET-MVC jQuery 不显眼的远程验证返回误报

php - 如何将两个数组合并在一起并使用 json_encode

c# - WebMatrix.WebData.WebSecurity - 如何仅通过 PasswordResetToken 获取用户名