How to send form data to controller using AJAX

To send form data to a controller using AJAX in an ASP.NET application, you can use the jQuery library to make the AJAX call. Here is an example of how to do this:

First, you'll need to create a form in your HTML markup. For example:

<form id="myForm">
    <input type="text" name="firstName" />
    <input type="text" name="lastName" />
    <input type="submit" value="Submit" />

</form>

Then, you can use jQuery to capture the form submit event and prevent the default form submission behavior. You can then use the `$.ajax()` method to send an AJAX request to the server, passing the form data as a JSON object.

$(function() {
    $('#myForm').submit(function(e) {
        e.preventDefault();
    
        var formData = $(this).serializeArray();
        var jsonData = {};
        
        $.each(formData, function(index, field) {
            jsonData[field.name] = field.value;
        });
        
        $.ajax({
            url: '/MyController/MyAction',
            type: 'POST',
            data: JSON.stringify(jsonData),
            contentType: 'application/json; charset=utf-8',
            success: function(data) {
                console.log(data);
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.log(textStatus, errorThrown);
            }
        });
    });

});

In this example, the `$.ajax()` method is called with the following parameters:

`url`: The URL of the controller action that will handle the request.

`type`: The HTTP method to use for the request (in this case, POST).

`data`: The data to send to the server (in this case, the form data as a JSON string).

`contentType`: The content type of the data being sent to the server.

`success`: A callback function that will be called if the request is successful.

`error`: A callback function that will be called if the request fails.


In the controller action that handles the request, you can use the `JsonRequestBehavior.AllowGet` option to allow the response to be returned as JSON:

public ActionResult MyAction(MyViewModel model)
{
    // Do something with the form data here...
    
    return Json(new { success = true }, JsonRequestBehavior.AllowGet);

}

In this example, the `MyAction()` method takes a `MyViewModel` object as a parameter. This object should contain properties that match the form data fields. You can then do whatever processing you need to do with the form data.

Finally, the method returns a JSON object that indicates whether the request was successful or not. The `JsonRequestBehavior.AllowGet` option is used to allow the response to be returned as JSON.

Previous Post Next Post