Home > Article > Web Front-end > How to Pass JSON POST Data to a Web API Method as an Object in ASP.NET MVC?
Passing JSON POST Data to Web API Method as an Object
In ASP.NET MVC, passing a customer object in JSON format through a POST request can result in null values in the customer parameter of the POST method. This issue arises due to the default Content-Type used by browsers, which is "application/x-www-form-urlencoded."
Solution
To rectify the problem, the Content-Type header must be set to "application/json" in the POST request. This can be achieved by using Content-Type: "application/json" in the header of the request, as demonstrated below:
$(function () { var customer = {contact_name :"Scott",company_name:"HP"}; $.ajax({ type: "POST", data :JSON.stringify(customer), url: "api/Customer", contentType: "application/json" }); });
By specifying the Content-Type as "application/json," the model binder will recognize and bind the JSON data to the corresponding class object accurately.
Passing Complex Objects
If the web API method parameter is a complex object, such as:
public class CustomerViewModel { public int Id {get; set;} public string Name {get; set;} public List<TagViewModel> Tags {get; set;} }
To send this object from the client-side, the following code can be used:
//Build an object which matches the structure of our view model class var model = { Name: "Shyju", Id: 123, Tags: [{ Id: 12, Code: "C" }, { Id: 33, Code: "Swift" }] }; $.ajax({ type: "POST", data: JSON.stringify(model), url: "../product/save", contentType: "application/json" }).done(function(res) { console.log('res', res); // Do something with the result :) });
Ensure [FromBody] Attribute
The web API method parameter must be decorated with the [FromBody] attribute to enable model binding from the request body. If this attribute is omitted, flat properties will be bound correctly, but complex properties will remain empty.
[HttpPost] public CustomerViewModel Save([FromBody] CustomerViewModel m) { return m; }
The above is the detailed content of How to Pass JSON POST Data to a Web API Method as an Object in ASP.NET MVC?. For more information, please follow other related articles on the PHP Chinese website!