Home » Jquery » jquery – Grab form values to avoid page reload when submitting a MVC form

jquery – Grab form values to avoid page reload when submitting a MVC form

Posted by: admin February 22, 2020 Leave a comment

Questions:

I have a ASP.NET razor form that looks something like:

@using (Html.BeginForm("CreateUser", "Users", FormMethod.Post, new { role = "form", id="create-user-form" }))
{

@Html.LabelFor(model => model.LastName)
                            @Html.EditorFor(model => model.LastName, new { htmlAttributes = new { @class = "form-control" } })
                            @Html.ValidationMessageFor(model => model.LastName, "", new { @class = "text-danger" })

}

Then in my controller:

public ActionResult CreateUser(UserViewModel viewModel)
{



}

Using jQuery, is it possible for me to grab the variables in the form and submit it to my controller such that the page doesn’t reload when the form submits?

Currently it does a post back and the page reloads, which I am trying to avoid in this situation.

How to&Answer:

You can either set up an AJAX call in jQuery, or you can utilize the jQuery Unobtrusive Ajax Nuget Package (I am more familiar with setting up this).

Using this package, you can take advantage of the Ajax submitform helper attribute.

The main purpose of this is to have one div section (encapsulated within the AJAX form element) that contains the input fields that are submitted. Then, when submitted, it calls a Partial View Result (that requires a return PartialView(); ) and displays it in your original parent view, without reloading the page.

Here is an example setup:

<div class="row">
    <div class="col-md-4"></div>
    <div class="col-md-4">
    @{using (Ajax.BeginForm("PartialViewResultName", "ControllerName", null, new AjaxOptions
      {
          HttpMethod = "GET",
          UpdateTargetId = "targetDivID",
          InsertionMode = InsertionMode.Replace,
          LoadingElementId = "targetDivLoadingID"
      }, new
      {
          id = "formID"
      }))
      {
          // Where your Html code that will be submitted goes
          <button type="submit">submit</button>
      }}
    </div>
    <div class="col-md-4"></div>
</div>
<div class="row">
    <div class="col-md-12">
        <div id="targetDivID"></div>
    </div>
</div>

Answer:

You can do this by using an Ajax function. If you do this, you can remove the @using block altogether.

First, add a button to your view and give it an id. also give your input field an id.

@Html.LabelFor(model => model.LastName)
@Html.EditorFor(model => model.LastName, new { htmlAttributes = new { @class = "form-control", @id = "lastName" } })
@Html.ValidationMessageFor(model => model.LastName, "", new { @class = "text-danger" })
<button type="button" class="btn btn-success" id="createButton">Add user</button>

Then add a script at the bottom of your code. The following assumes you have this code in your _Layout.cshtml file: @RenderSection("scripts", required: false)
If not, don’t wrap the script tags in this bit of code: @section Scripts {}

@section Scripts {
<script>
        // listen for button click event
        $('#createButton').click(function (e) {
            e.preventDefault();

            let lastName = $('#lastName').val();

            // Check for empty input -> exit if empty
            if ($.trim(lastName) == "") {
                return;
            }

            let data = JSON.stringify({
                lastName: lastName
            });

            // call saveUser ajax function, pass in data
            $.when(saveUser(data)).then(function (response) {
                alert(response);
            }).fail(function (err) {
                console.log(err);
            });
        });

        // Pass all data to Controller for saving
        function saveUser(data) {
            return $.ajax({
                url: '/Users/CreateUser',
                dataType: 'json',
                type: 'POST',
                contentType: 'application/json; charset=utf-8',
                processData: false,
                cache: false,
                data: data,
                success: function (result) {
                    console.log(result);
                },
                error: function () {
                    alert('Error! Please contact an administrator if the problem persists.')
                }
            });
        }
    </script>
}

Finally, set up your controller action something like this:

[HttpPost]
public JsonResult CreateUser(string lastName)
{
    // prepare a return statement
    string result = "Error! Please contact an administrator if the problem persists.";

    // perform your create logic here, then check if it succeeded or not


    if (createSucceeded == true)
    {
        // change result string to a success message
        result = "Success! User created!";
    }

    // Return the result string
    return Json(result, JsonRequestBehavior.AllowGet);
}