使用内置功能在 MVC6 中使用 JQuery AJAX 提交剃刀表单

Submitting a razor form using JQuery AJAX in MVC6 using the built-in functionality(使用内置功能在 MVC6 中使用 JQuery AJAX 提交剃刀表单)
本文介绍了使用内置功能在 MVC6 中使用 JQuery AJAX 提交剃刀表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我想知道在 MVC6 中是否有使用 jQuery AJAX 提交表单的特定方法,仍然使用 ASP.NET MVC 的自动绑定功能.我相信在其他版本的 MVC 中,您可以使用 jquery.unobtrusive-ajax 并简单地使用

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(){}

由于 MVC6 发生了一些变化,我想知道除了在提交表单时向服务器执行正常的 AJAX 发布之外,新推荐的方法是什么.这意味着我将手动获取每个输入字段的值,将它们转换为 JSON 并将它们发送到控制器,以便所有内容都绑定到 ViewModel.

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.

如果我将以下 JavaScript 用于 AJAX,那么任何 AJAX 表单设置是否重要?

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"
    });
});

推荐答案

Ajax 的工作方式相同,但使用新的 MVC 6 Tag Helper 代替 @Ajax 帮助器(不要忘记引用 'jquery' 和 'jquery.unobtrusive-ajax 脚本).

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 存在于 Asp.Net GitHub repo 中,可以被 Bower 拉取.

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

使用新的 MVC TagHelpers,您只需声明如下形式:

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>

要使用以前 MVC 版本的 Ajax Helper 上存在的 AjaxOptions,只需添加这些属性,执行 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>

您可以在表单中使用的 HTML 属性(以前称为 AjaxOptions)如下(原文出处):

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               |
+------------------------+-----------------------------+

另一个重大变化是如何在服务器端检查请求是否确实是 AJAX 请求.在以前的版本中,我们只是使用 Request.IsAjaxRequest().

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().

在 MVC6 上,您必须创建一个简单的扩展来添加与以前的 MVC 版本相同的选项(原文出处):

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;
}

这篇关于使用内置功能在 MVC6 中使用 JQuery AJAX 提交剃刀表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

ajax请求获取json数据并处理的实例代码 $.ajax({ type: 'GET', url: 'https://localhost:44369/UserInfo/EditUserJson',//请求数据 data: json,//传递数据 //dataType:'json/text',//预计服务器返回的类型 timeout: 3000,//请求超时的时间 //回调函数传参 suc
在开发JS过程中,会经常遇到两个小数相运算的情况,但是运算结果却与预期不同,调试一下发现计算结果竟然有那么长一串尾巴。如下图所示: 产生原因: JavaScript对小数运算会先转成二进制,运算完毕再转回十进制,过程中会有丢失,不过不是所有的小数间运算会
append() 方法在被选元素的结尾(仍然在内部)插入指定内容。 语法: $(selector).append( content ) var creatPrintList = function(data){ var innerHtml = ""; for(var i =0;i data.length;i++){ innerHtml +="li class='contentLi'"; innerHtml +="a href
问题描述: 在javascript中引用js代码,然后导致反斜杠丢失,发现字符串中的所有\信息丢失。比如在js中引用input type=text onkeyup=value=value.replace(/[^\d]/g,) ,结果导致正则表达式中的\丢失。 问题原因: 该字符串含有\,javascript对字符串进行了转
Rails/Javascript: How to inject rails variables into (very) simple javascript(Rails/Javascript:如何将 rails 变量注入(非常)简单的 javascript)
Rails 3.1 ajax:success handling(Rails 3.1 ajax:成功处理)