Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Submitting a razor form using JQuery AJAX in MVC6 using the built-in functionality

I would like to know if there is a specific way to submit a form using jQuery AJAX in MVC6, still using the Auto Binding features of ASP.NET MVC. I believe in other versions of MVC you could use jquery.unobtrusive-ajax and simply use

@using (Ajax.BeginForm("SaveData", new AjaxOptions(){}

Since there have been some changes with MVC6 I am wondering what the new recommended way to do this would be besides doing a normal AJAX post to the server when the form is submitted. This meaning I would manually get the values of each input field, turn them into JSON and send them over to the controller so everything will get bound to the ViewModel.

If I use the following JavaScript for AJAX do any of the AJAX form settings even matter?

$('form').submit(function () {
    $.ajax({
        type: "POST",
        url: "/Products/Create/",
        data: JSON.stringify(data),
        contentType: "application/json; charset=utf-8",
        dataType: "json"
    });
});
like image 875
Blake Rivell Avatar asked Feb 04 '16 13:02

Blake Rivell


2 Answers

Ajax works the same way, but instead of the @Ajax helper's, use the new MVC 6 Tag Helpers (don't forget to reference 'jquery' and 'jquery.unobtrusive-ajax' scripts).

JQuery Unobtrusive Ajax exists in the Asp.Net GitHub repo and can be Bower pulled.

Using the new MVC TagHelpers, you simply declare the form like the following:

<form asp-controller="Home" asp-action="SaveForm" data-ajax="true" data-ajax-method="POST">
...
</form>

To use the AjaxOptions that existed on the Ajax Helper on previous MVC versions, just add those attributes do the form tag like this:

<form asp-controller="Home" asp-action="SaveForm" data-ajax="true" data-ajax-method="POST" data-ajax-mode="replace" data-ajax-update="#content">
...
</form>
<div id="content"></div>

The HTML attributes (formerly AjaxOptions) that you can use in the form are the following (original source):

+------------------------+-----------------------------+
|      AjaxOptions       |       HTML attribute        |
+------------------------+-----------------------------+
| Confirm                | data-ajax-confirm           |
| HttpMethod             | data-ajax-method            |
| InsertionMode          | data-ajax-mode              |
| LoadingElementDuration | data-ajax-loading-duration  |
| LoadingElementId       | data-ajax-loading           |
| OnBegin                | data-ajax-begin             |
| OnComplete             | data-ajax-complete          |
| OnFailure              | data-ajax-failure           |
| OnSuccess              | data-ajax-success           |
| UpdateTargetId         | data-ajax-update            |
| Url                    | data-ajax-url               |
+------------------------+-----------------------------+

Another significant change is how you check on the server side if the request is indeed an AJAX request. On previous versions we simply used Request.IsAjaxRequest().

On MVC6, you have to create a simple extension to add the same options that existed on previous MVC versions (original source):

/// <summary>
/// Determines whether the specified HTTP request is an AJAX request.
/// </summary>
/// 
/// <returns>
/// true if the specified HTTP request is an AJAX request; otherwise, false.
/// </returns>
/// <param name="request">The HTTP request.</param><exception cref="T:System.ArgumentNullException">The <paramref name="request"/> parameter is null (Nothing in Visual Basic).</exception>
public static bool IsAjaxRequest(this HttpRequest request)
{
  if (request == null)
    throw new ArgumentNullException("request");

  if (request.Headers != null)
    return request.Headers["X-Requested-With"] == "XMLHttpRequest";
  return false;
}
like image 88
João Pereira Avatar answered Oct 02 '22 04:10

João Pereira


Here's a really nice YouTube tutorial on AJAX forms, and you can download the project from this GitHub link. It contain the script to be used for AJAX.

Sample style copied from the above project:

<form asp-controller="Home1" asp-action="SaveForm" 
      data-ajax="true" 
      data-ajax-method="POST"
      data-ajax-mode="replace" 
      data-ajax-update="#content"
      data-ajax-loading  ="#divloading"
      data-ajax-success="Success"
      data-ajax-failure ="Failure">
    <div class="form-group">
        <div>  <h4>@Html.Label("Name")</h4> </div>
        <div>  @Html.TextBox("Name","",htmlAttributes:new { @class="form-control",id="Name"})</div>
    </div>
    <div class="form-group">
        <div><h4>@Html.Label("Age")</h4></div>
        <div>@Html.TextBox("Age", "", htmlAttributes: new { @class = "form-control", id ="Age" })</div>
    </div>
    <br/>
    <input type="submit" name="Submit"  class="btn btn-block btn-success" />
</form>
like image 4
Amneu Avatar answered Oct 02 '22 06:10

Amneu