How to pass form data to controller in MVC using Ajax

You can pass form data to a controller in an ASP.NET MVC application using Ajax by making an Ajax request to the controller action method with the form data as a parameter. Here's an example of how to do it:

HTML form:

<form id="myForm">

    <input type="text" name="name" id="name">

    <input type="email" name="email" id="email">

    <input type="submit" value="Submit">

</form>

JavaScript code to submit the form data via Ajax:

$("#myForm").submit(function(event) {
    event.preventDefault();
    var formData = $(this).serialize();
    $.ajax({
        url: "/ControllerName/ActionName",
        type: "POST",
        data: formData,
        success: function(result) {
            // handle success
        },
        error: function(xhr, status, error) {
            // handle error
        }
    });

});

In the above code, the `$("#myForm").submit()` function is called when the form is submitted. The `event.preventDefault()` function is used to prevent the default form submission behavior, which would cause a page reload.

The `$(this).serialize()` function is used to serialize the form data into a URL-encoded string that can be sent to the server in the Ajax request.

The `$.ajax()` function is then used to send the form data to the controller action method. The `url` parameter specifies the URL of the controller action method, and the `data` parameter contains the serialized form data.

In the controller action method, you can receive the form data as a parameter of the action method. The parameter can be of the type `FormCollection`, which is a collection of all the form values submitted in the request. Alternatively, you can create a model class that represents the form data and receive that as the parameter.

Here's an example of how to receive the form data as a `FormCollection` parameter in the controller action method:

[HttpPost]

public ActionResult ActionName(FormCollection form)

{

    string name = form["name"];

    string email = form["email"];

    // process the form data

    return View();

}

In this example, the `ActionName` method is decorated with the `[HttpPost]` attribute to indicate that it should be called when an HTTP POST request is received. The `FormCollection` parameter is used to receive the form data, and the `name` and `email` values are retrieved from the form collection. You can then process the form data as needed and return a view.

Previous Post Next Post