To send JSON data to a controller using Ajax in MVC, you can follow these steps:
- Create a JSON object with the data that you want to send. For example:
var data = {name: "John",age: 30,city: "New York"};
- Use the `JSON.stringify()` method to convert the JSON object to a string. This is necessary because Ajax requests can only send data in string format. For example:
var dataString = JSON.stringify(data);
- Set the `Content-Type` header to `application/json` to indicate that you are sending JSON data. For example:
$.ajax({url: "/Controller/Action",type: "POST",data: dataString,contentType: "application/json; charset=utf-8",dataType: "json",success: function (result) {// Handle success},error: function (xhr, status, error) {// Handle error}});
- In your controller action, use the `[FromBody]` attribute to indicate that the data is coming from the request body and use a parameter of type `dynamic` to receive the JSON data. For example:
[HttpPost]public ActionResult Action([FromBody] dynamic data){string name = data.name;int age = data.age;string city = data.city;// Process the datareturn Json(new { success = true });}
Note that in this example, the action returns a JSON result with a `success` property set to `true`. You can customize the response as needed for your specific use case.