【问题标题】:how to post form data to API controller如何将表单数据发布到 API 控制器
【发布时间】:2016-07-12 09:45:42
【问题描述】:

使用 jquery 发布表单数据:

$.ajax('API/Validate/Customer?column=1&rowid=2&vmnr=3&isik=4',
   {
       data: JSON.stringify({
           headerData: $("#_form").serializeArray()
       }),
       async: false,
       contentType: "application/json; charset=utf-8",
       dataType: "json",
       type: "POST"
   });

由 ASP.NET MVC4 Web API 控制器验证接收:

public class ValidateController : ApiController
{
    public class Body
    {
        public Dictionary<string, string> headerData { get; set; }
        public Dictionary<string, string> rowData { get; set; }
    }

    public HttpResponseMessage Validate(
        string id,
        string column,
        string rowid,
        int? vmnr,
        string isik,
        [FromBody] Body body,

        string dok = null,
        string culture = null,
        uint? company = null
       )
    { ...

body.headerData 值在控制器中为空。

根据回答 How to receive dynamic data in Web API controller Post method

body.headerData 必须有表单键。 但是,它是空的。

如何在控制器中获取 headerData 作为键、值对?

Chorme 开发者工具显示正确的 json 发布在正文中:

{"headerData":[{"name":"Kalktoode","value":"kllöklö"},
               {"name":"Kaal","value":""}
              ]}

我试图删除

 public Dictionary<string, string> rowData { get; set; }

上课,但问题仍然存在。

【问题讨论】:

  • 你必须在Validate方法中添加一个属性[HttpPost]
  • 我添加了,但问题仍然存在。在引用的答案中,数据在没有数组的键值对中传递。也许数据不应该序列化为数组?如果是,它如何像引用答案中的 json 数据一样序列化?
  • 我认为你的 headerData 应该看起来像这样 {"headerData":[{"Kalktoode":"kllöklö"}, {"Kaal":""}]} .. 没有名称,值。
  • 是否应该使用stackoverflow.com/questions/1184624/…的代码形式进行序列化?

标签: jquery asp.net asp.net-mvc asp.net-mvc-4 asp.net-web-api


【解决方案1】:

您的控制器与您发送的内容不匹配

确实,您的控制器将反序列化主体,如:

{
  "headerData": {"someKey":"someValue", "otherKEy":"otherValue"},
  "rowData": {"someKey":"someKey"}
}

不是您实际发送的 JSON 的结构。 您的控制器会查找具有 2 个成员的主体 beeing Dictionnaries,而不是 键值对数组

如果您希望控制器使用键值对数组

通过键值数组,我的意思是:

{
  "headerData": [
    {
      "key": "string",
      "value": "string"
    }
  ],
  "rowData": [
    {
      "key": "string",
      "value": "string"
    }
  ]
}

您需要将 Body 对象更新为:

  [HttpPost, Route("test")]
  public void Test(Body b)
  {
  }

  public class Body
  {
      public List<KeyValuePair<string,string>> headerData { get; set; }
      public List<KeyValuePair<string,string>> rowData { get; set; }
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-06
    • 2021-04-01
    • 1970-01-01
    • 2017-11-10
    • 2014-01-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多