jQuery JSON Data Posting to ASP .NET MVC 4 Controller Action
Overview
When working with ASP .NET MVC 4, it's common to use jQuery to post JSON data to a controller action. This can be useful for updating data on the server without reloading the page. In this article, we'll walk through the steps to accomplish this task.
Step 1: Create the Controller Action
The first step is to create a controller action that will handle the JSON data. In this example, we'll create an action called "UpdateData".
public ActionResult UpdateData(MyModel data)
{
// Update data on the server
return Json(new { success = true });
}
Step 2: Create the jQuery Code
Next, we'll create the jQuery code that will post the JSON data to the controller action. We'll use the $.ajax() method to make the post request.
var data = { name: "John", age: "35" };
$.ajax({
type: "POST",
url: "/MyController/UpdateData",
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert("Data updated successfully.");
},
error: function () {
alert("An error occurred.");
}
});
Step 3: Test the Code
Finally, we'll test the code to make sure everything is working correctly. When we run the code, it should post the JSON data to the controller action and return a success message.
Conclusion
In this article, we've walked through the steps to post JSON data to an ASP .NET MVC 4 controller action using jQuery. By following these steps, you should be able to update data on the server without reloading the page.
Leave a Reply
Related posts