Andrus
Andrus

Reputation: 27899

how to post form data to API controller

Form data is posted using 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"
   });

It is received by ASP.NET MVC4 Web API controller Validate:

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 value is null in controller.

According to answer in How to receive dynamic data in Web API controller Post method

body.headerData must have form keys. However, it is empty.

How to get headerData as key, value pairs in controller ?

Chorme developer tools show that proper json is posted in body:

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

I tried to remove

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

from class but problem persists.

Upvotes: 2

Views: 1095

Answers (1)

plog17
plog17

Reputation: 832

Your controller does not match with what you are sending

Indeed, your controller will deserialize body like:

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

And it is not the structure of the JSON you actually send. Your controller looks for a body with 2 members beeing Dictionnaries, not Arrays of key value pair.

If you want your controller to work with Arrays of key value pair

By array of key value, I mean something like:

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

You need to update your Body object to:

  [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; }
  }

Upvotes: 2

Related Questions