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
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:
To use the AjaxOptions that existed on the Ajax Helper on previous MVC versions, just add those attributes do the form tag like this:
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):
///
/// Determines whether the specified HTTP request is an AJAX request.
///
///
///
/// true if the specified HTTP request is an AJAX request; otherwise, false.
///
/// The HTTP request.The parameter is null (Nothing in Visual Basic).
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;
}