【问题标题】:Multiple Bind(Prefix = "...") in ASP.Net Core 3 MVCASP.Net Core 3 MVC 中的多个绑定(前缀 =“...”)
【发布时间】:2019-10-03 14:40:58
【问题描述】:

我有一个 ASP.Net MVC 4 应用程序,我将其移植到 ASP.Net Core 3.0 MVC。

我正在尝试移植此方法

[HttpPost]
public ActionResult DoSave(
  [Bind(Prefix = "new")]IEnumerable<C_Data> newItems,
  [Bind(Prefix = "updated")]IEnumerable<C_Data> updatedItems,
  [Bind(Prefix = "deleted")]IEnumerable<C_Data> deletedItems))
{
}

在帖子 AJAX 中(在 Web 浏览器的 JavaScript 中)我将值作为 JSON 像这样发送

{
  "new[0].Id":3,
  "new[0].SID":"00000000-0000-0000-0000-000000000000",
  "new[0].Name":"asd"
}

这是 C_Data 类

public class C_Data
{
    [Key]
    public int Id { get; set; }

    public Guid SID { get; set; }

    [Required]
    [MaxLength(40)]
    public string Name { get; set; }
}

但是这个动作执行的时候三个参数都是空的。

这是我在 ModelState

中遇到的错误

“无法将 JSON 值转换为 C_Data”

谁能告诉我如何移植这个方法?

谢谢。

PD:此操作在 MVC 控制器而非 API 控制器中。

【问题讨论】:

  • How to use Bind Prefix?的可能重复
  • 你知道BindAttribute 是用于表单而不是json?你的 json 应该是 {"newItems":[{"Id" : 3,"SID":...}], "updatedItems":[...]}

标签: c# asp.net-mvc asp.net-core


【解决方案1】:

这里是a link,应该会有所帮助。

看起来您应该能够使用 C_Data 对象,将其放入数组中,并在 AJAX 调用中对其进行字符串化,接收 IEnumerable。

【讨论】:

    【解决方案2】:

    对于Asp.Net Core,绑定模型有两种方式,ModelBindingJsonInputFormatter。使用 json 发送请求,它将使用JsonInputFormatter,而Bind 将不起作用。

    一般来说,我建议您尝试以下选项:

    1. 控制器动作

      [HttpPost]
      public ActionResult DoSave([FromBody]ItemModel itemModel)
      {
          return Ok("Worked");     
      }
      
    2. 型号

      public class ItemModel
      {
          public IEnumerable<C_Data> NewItems { get; set; }
          public IEnumerable<C_Data> UpdatedItems { get; set; }
          public IEnumerable<C_Data> DeletedItems { get; set; }
      
      }
      
    3. 请求 Json

      {
          "newItems":[{
              "Id":3,
              "SID":"00000000-0000-0000-0000-000000000000",
              "Name":"asd"
          }]
      }
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-11-30
      • 2020-05-26
      • 1970-01-01
      • 2020-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多