Home >Web Front-end >JS Tutorial >How to Pass JSON POST Data as an Object to a Web API Method in ASP.NET MVC4?

How to Pass JSON POST Data as an Object to a Web API Method in ASP.NET MVC4?

Barbara Streisand
Barbara StreisandOriginal
2024-11-09 14:13:02344browse

How to Pass JSON POST Data as an Object to a Web API Method in ASP.NET MVC4?

Passing JSON POST Data as an Object to a Web API Method

In ASP.NET MVC4 Web API, you may encounter a scenario where a POST request containing JSON data needs to be passed to an action method as an object. However, without proper configuration, the action method's parameter may contain null properties. To resolve this issue, you must take the following steps:

1. Specify Content-Type as "application/json":

When sending the request, ensure that the Content-Type header is set to "application/json." This informs the server that the data is in JSON format.

2. Use JSON.stringify Method:

In the client-side code, convert the JSON data to a JSON string using the JSON.stringify method. This step is crucial for the model binder to bind the JSON data to your class object.

Example:

var customer = { contact_name: "Scott", company_name: "HP" };
$.ajax({
    type: "POST",
    data: JSON.stringify(customer),
    url: "api/Customer",
    contentType: "application/json"
});

3. Decorate Action Method Parameter with [FromBody]:

In the Web API action method, decorate the parameter that will receive the JSON data with [FromBody]. This attribute indicates that the data should be bound from the request body.

Example:

public IActionResult Post([FromBody] Customer customer)
{
    // ...
}

4. Posting Complex Objects:

If your view model class contains complex properties (such as lists or nested classes), the same principles apply. Ensure that the client-side code builds an object that matches the structure of the class and sends it as JSON data with the correct Content-Type.

Troubleshooting:

  • If model binding works for some properties but not others, check if the action method parameter is decorated with [FromBody].
  • If you are not explicitly setting the Content-Type, ensure that your client-side code is using the correct method (e.g., $.ajax with contentType set to "application/json").

The above is the detailed content of How to Pass JSON POST Data as an Object to a Web API Method in ASP.NET MVC4?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn