Posting JSON Data to ASP.NET MVC with Code Examples

To post JSON data to an ASP.NET MVC controller, you can use AJAX to send the data from a client-side application to the server. Here's an example of how to do this with jQuery, but you can use other JavaScript libraries or vanilla JavaScript as well.

Assuming you have a model in your ASP.NET MVC application like this:

public class MyModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    // Other properties
}

Here's how you can post JSON data to a controller action:

  1. Create a Controller Action to Receive JSON Data:
public class MyController : Controller
{
    [HttpPost]
    public JsonResult SaveMyModel([FromBody] MyModel model)
    {
        // Process and save the model data
        return Json(new { success = true, message = "Data saved successfully" });
    }
}

In this example, the SaveMyModel action expects to receive JSON data in the model parameter.

  1. Create a View for the HTML Form:

You'll need an HTML form to capture data from the user. Here's a simple example:

@using (Html.BeginForm("SaveMyModel", "My", FormMethod.Post, new { id = "myForm" }))
{
    @Html.AntiForgeryToken()
    <input type="text" id="Name" name="Name" />
    <!-- Other input fields for your model -->
    <input type="submit" value="Submit" />
}
  1. Use jQuery to Post JSON Data:

Include jQuery in your view, and add a script to handle the form submission as JSON data.

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>


    $(document).ready(function () {
        $("#myForm").submit(function (e) {
            e.preventDefault(); // Prevent the default form submission

            var formData = {
                Id: 0, // Set the Id as needed
                Name: $("#Name").val(),
                // Add other properties as needed
            };

            $.ajax({
                url: "/My/SaveMyModel",
                type: "POST",
                data: JSON.stringify(formData),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (result) {
                    if (result.success) {
                        alert(result.message);
                    } else {
                        alert("An error occurred.");
                    }
                }
            });
        });
    });

This jQuery script captures the form data, converts it to JSON, and sends it to the server using AJAX.

Make sure you have the necessary scripts and libraries referenced in your project, and adjust the code according to your specific requirements.

 
Asp.Net Ajax Control Toolkit tutorials.

Give your valuable comments.

Name
Email
Comment
8 + 8 =
 

About Us | Terms of Use | Privacy Policy | Disclaimer | Contact Us Copyright © 2012-2024 CodingFusion
50+ C# Programs for beginners to practice