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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35202804/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 17:23:39  来源:igfitidea点击:

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

javascriptjqueryajaxasp.net-mvcasp.net-core-mvc

提问by Blake Rivell

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

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

@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.

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

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

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

$('form').submit(function () {
    $.ajax({
        type: "POST",
        url: "/Products/Create/",
        data: JSON.stringify(data),
        contentType: "application/json; charset=utf-8",
        dataType: "json"
    });
});

回答by Jo?o Pereira

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

Ajax 的工作方式相同,但使用新的 MVC 6 Tag Helpers(不要忘记引用 'jquery' 和 'jquery.unobtrusive-ajax' 脚本)而不是 @Ajax 助手。

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

JQuery Unobtrusive Ajax存在于 Asp.Net GitHub 存储库中,可以被 Bower 拉取。

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

使用新的 MVC TagHelpers,您只需像下面这样声明表单:

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

要使用以前 MVC 版本的 Ajax Helper 上存在的 AjaxOptions,只需将这些属性添加到表单标记中,如下所示:

<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):

您可以在表单中使用的 HTML 属性(以前称为 AjaxOptions)如下(原始来源):

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

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

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

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

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

回答by Amneu

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.

这是一个关于 AJAX 表单的非常好的YouTube 教程,您可以从此GitHub 链接下载该项目。它包含用于 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>

回答by Behrouz Goudarzi

https://github.com/Behrouz-Goudarzi/AjaxTagHelper

https://github.com/Behrouz-Goudarzi/AjaxTagHelper

AjaxTagHelper

AjaxTagHelper

A simple solution to using links and ajax forms using Tag Helper in aspnet core

在aspnet核心中使用Tag Helper使用链接和ajax表单的简单解决方案

First, copy the AjaxTagHelper class from the Extensions folder to your project.

首先,将 AjaxTagHelper 类从 Extensions 文件夹复制到您的项目中。

Second, copy the AjaxTagHelper.js file from js folder in wwwroot and add it to your project.

其次,从 wwwroot 的 js 文件夹中复制 AjaxTagHelper.js 文件并将其添加到您的项目中。

Then do the following: Open the viewImports file and add the following code

然后执行以下操作: 打开 viewImports 文件并添加以下代码

@using AjaxTagHelper.Extensions
@using AjaxTagHelper
@using AjaxTagHelper.Models
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper *, AjaxTagHelper

To use Action Ajax, add the following code instead of the tag.

要使用 Action Ajax,请添加以下代码而不是标记。

  <ajax-action ajax-action="Delete" ajax-controller="Home" ajax-data-id="@Model.Id"
                 class="btn btn-danger btn-sm" ajax-success-func="SuccessDelete">
        Delete
    </ajax-action>

Use the following code to use AJAX to send the form to server.

使用以下代码使用 AJAX 将表单发送到服务器。

<div class="row">
    <form id="frmCreate" class="col-sm-9">
        <div class="row">
            <div class="col-sm-4 form-control">
                <input placeholder="Enter Name" name="Name" class="input-group" type="text" />
            </div>
            <div class="col-sm-4 form-control">
                <input placeholder="Enter Family" name="Family" class="input-group" type="text" />
            </div>
            <div class="col-sm-4 form-control">
                <input placeholder="Enter [email protected] " name="Email" class="input-group" type="email" />
            </div>
        </div>
    </form>
    <div class="col-sm-3">
        <ajax-button ajax-controller="Home" ajax-action="Create" ajax-form-id="frmCreate" ajax-success-func="SuccessCreate"
                     class="btn btn-sm btn-success">
            Create
        </ajax-button>
    </div>
</div>

Finally, add the scripts you need to view it, check the code below

最后,添加你需要查看的脚本,查看下面的代码

<script>
    function SuccessCreate(data) {
        console.log(data);
        $("#tbodyPerson").append(data);


    }
    function SuccessDelete(data) {
        $("#tr" + data.id).fadeOut();
    }
</script>
<script src="~/js/AjaxHelper.js"></script>