Ajax.BeginForm 不触发 AJAX 脚本,依赖回发

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21831451/
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-09-06 10:23:48  来源:igfitidea点击:

Ajax.BeginForm doesn't fire AJAX script, falls back on postback

ajaxasp.net-mvc-5

提问by Tentux

I will update this problem with the solution, I wanted to include my problem and solution as I wasn't able to find it on Stackoverflow. If you want to jump in with the solution, feel free.

我将用解决方案更新这个问题,我想包括我的问题和解决方案,因为我无法在 Stackoverflow 上找到它。如果您想加入解决方案,请随意。

I have a newly created 'Empty' MVC5 project created using Visual Studio 2013. I needed a from and wanted AJAX behavior if possible. Using Ajax.BeginForm was always straight-forward in MVC3 so I thought it would be in MVC5 also.

我有一个使用 Visual Studio 2013 创建的新创建的“空”MVC5 项目。如果可能,我需要一个 from 并希望 AJAX 行为。在 MVC3 中使用 Ajax.BeginForm 总是很直接,所以我认为它也可以在 MVC5 中使用。

However none of the javascript functions I've specified in OnBegin, OnFailure or OnSuccess inside the AjaxOptions are invoked when I click the submit button. Instead an Ajaxless post is sent to the server, this has shown to be true by examining Request.IsAjaxRequest which returns false.

但是,当我单击提交按钮时,我在 AjaxOptions 中的 OnBegin、OnFailure 或 OnSuccess 中指定的任何 javascript 函数都不会被调用。相反,一个 Ajaxless 帖子被发送到服务器,通过检查返回 false 的 Request.IsAjaxRequest 已经证明这是真的。

I have concluded that for some reason, then, ajax isn't being used at all. I've checked a number of things such as web.config, my layout scripts, etc.

我得出的结论是,出于某种原因,根本没有使用 ajax。我检查了很多东西,比如 web.config、我的布局脚本等。

My layout includes the following scripts:

我的布局包括以下脚本:

<script src="~/Scripts/jquery-1.5.1.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

My web.config includes:

我的 web.config 包括:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <appSettings>
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>
</configuration>

My view:

我的看法:

@model ContactEnquiryViewModel

@{
AjaxOptions ContactOptions = new AjaxOptions()
{
    OnBegin = "OnConactFormBegin()",    
    OnSuccess = "OnContactFormSuccess()",
    OnFailure = "OnContactFormFailure()"
    };
}

<div id="EnquiryFormContainer">

@using (Ajax.BeginForm("Contact", "Home", new { formName = "EnquiryForm" }, ContactOptions))
    {
    @Html.HiddenFor(m => m.Subject)

    <div class="field">
        @Html.LabelFor(m => m.FirstName)
        @Html.TextBoxFor(m => m.FirstName)
        <div class="validation">
            @Html.ValidationMessageFor(m => m.FirstName)
        </div>
    </div>

    <div class="field">
        @Html.LabelFor(m => m.LastName)
        @Html.TextBoxFor(m => m.LastName)
        <div class="validation">
            @Html.ValidationMessageFor(m => m.LastName)
        </div>
    </div>

    <div class="field">
        @Html.LabelFor(m => m.Email)
        @Html.TextBoxFor(m => m.Email)
        <div class="validation">
            @Html.ValidationMessageFor(m => m.Email)
        </div>
    </div>

    <div class="field">
        @Html.LabelFor(m => m.PhoneNumber)
        @Html.TextBoxFor(m => m.PhoneNumber)
        <div class="validation">
            @Html.ValidationMessageFor(m => m.PhoneNumber)
        </div>
    </div>

    <div class="field">
        @Html.LabelFor(m => m.Comments)
        @Html.TextAreaFor(m => m.Comments)
        <div class="validation">
            @Html.ValidationMessageFor(m => m.Comments)
        </div>
    </div>

    <div id="submitButtonContainer">
        <input type="submit" value="Submit" name="submit" />
    </div>
    }
</div>

My controller action (unfinished):

我的控制器操作(未完成):

[HttpPost]
public ActionResult Contact(ContactViewModel viewModel, String formName = "")
    {
    if (Request.IsAjaxRequest())
        {
        return new EmptyResult();               
        }

    return new EmptyResult();
    }

I have checked some other posts on this problem, and couldn't find a solution. Though some hinted at the possible solution, I was confused by the Microsoft CDN (http://www.asp.net/ajaxlibrary/cdn.ashx).

我查看了一些关于此问题的其他帖子,但找不到解决方案。尽管有些人暗示了可能的解决方案,但我对 Microsoft CDN ( http://www.asp.net/ajaxlibrary/cdn.ashx)感到困惑。

On the Microsoft CDN they have the following section:

在 Microsoft CDN 上,他们有以下部分:

The following ASP.NET MVC JavaScript files are hosted on this CDN:

以下 ASP.NET MVC JavaScript 文件托管在此 CDN 上:

ASP.NET MVC 5.0

http://ajax.aspnetcdn.com/ajax/mvc/5.0/jquery.validate.unobtrusive.js
http://ajax.aspnetcdn.com/ajax/mvc/5.0/jquery.validate.unobtrusive.min.js

ASP.NET MVC 4.0

http://ajax.aspnetcdn.com/ajax/mvc/4.0/jquery.validate.unobtrusive.js
http://ajax.aspnetcdn.com/ajax/mvc/4.0/jquery.validate.unobtrusive.min.js

ASP.NET MVC 3.0

http://ajax.aspnetcdn.com/ajax/mvc/3.0/jquery.unobtrusive-ajax.js
http://ajax.aspnetcdn.com/ajax/mvc/3.0/jquery.unobtrusive-ajax.min.js
http://ajax.aspnetcdn.com/ajax/mvc/3.0/jquery.validate.unobtrusive.js
http://ajax.aspnetcdn.com/ajax/mvc/3.0/jquery.validate.unobtrusive.min.js
http://ajax.aspnetcdn.com/ajax/mvc/3.0/MicrosoftMvcAjax.js
http://ajax.aspnetcdn.com/ajax/mvc/3.0/MicrosoftMvcAjax.debug.js 

ASP.NET MVC 2.0

http://ajax.aspnetcdn.com/ajax/mvc/2.0/MicrosoftMvcAjax.js
http://ajax.aspnetcdn.com/ajax/mvc/2.0/MicrosoftMvcAjax.debug.js 

ASP.NET MVC 1.0

http://ajax.aspnetcdn.com/ajax/mvc/1.0/MicrosoftMvcAjax.js
http://ajax.aspnetcdn.com/ajax/mvc/1.0/MicrosoftMvcAjax.debug.js 

They would seem to suggest the only script you'll need for MVC5 is jquery.validate.unobtrusive.

他们似乎认为 MVC5 需要的唯一脚本是 jquery.validate.unobtrusive。

采纳答案by Tentux

Everything has started working since I included the following script in my layout:

自从我在布局中包含以下脚本以来,一切都开始工作了:

<script src="http://ajax.aspnetcdn.com/ajax/mvc/3.0/jquery.unobtrusive-ajax.min.js"></script>

On the Microsoft CDN it looks as though this script is MVC3-specific.

在 Microsoft CDN 上,这个脚本似乎是特定于 MVC3 的。

Feel free to contribute better ways if possible, or answer the question: "Why isn't this script included in the MVC project template (VS2013)?"

如果可能,请随意贡献更好的方法,或回答以下问题:“为什么此脚本未包含在 MVC 项目模板 (VS2013) 中?”

回答by RitchieD

To get a local copy as part of your MVC project" From VS2013, right click on your MVC 5 project, select "Manage NuGet Packages". Select "Online" and search for "jquery.unobtrusive-ajax", Then Install "Microsoft.jQuery.Unobtrusive.Ajax".

获取本地副本作为 MVC 项目的一部分”从 VS2013,右键单击您的 MVC 5 项目,选择“管理 NuGet 包”。选择“在线”并搜索“jquery.unobtrusive-ajax”,然后安装“Microsoft. jQuery.Unobtrusive.Ajax”。

回答by user3201809

I had the same issue on a dummy MVC5 project.

我在一个虚拟的 MVC5 项目上遇到了同样的问题。

Add this to your BundleConfig

将此添加到您的 BundleConfig

        bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                    "~/Scripts/jquery.unobtrusive*",
                    "~/Scripts/jquery.validate*"));

Add this to your layout.cshtml

将此添加到您的 layout.cshtml

@Scripts.Render("~/bundles/jqueryval")

I didn't add any new files to my projects so if you have an MVC 4 or 5 web project, I doubt if you would need to add any extra js files.

我没有在我的项目中添加任何新文件,所以如果你有一个 MVC 4 或 5 web 项目,我怀疑你是否需要添加任何额外的 js 文件。

It solved my issue. I hope it solves yours.

它解决了我的问题。我希望它能解决你的问题。

回答by Cagatay Kalan

Did you check if your web.config file contains

您是否检查过您的 web.config 文件是否包含

<appSettings>
    <!-- this one is for client side validation -->
    <add key="ClientValidationEnabled" value="true" />

    <!-- this is for unobtrusive ajax -->
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>

回答by Alexander

Adding reference to the javascript file jquery.unobtrusive-ajax.jsworked for me.

添加对 javascript 文件jquery.unobtrusive-ajax.js 的引用对我有用

回答by Erez breiman

I had the same issue and the solution was actually to make sure that the script references are in the right order (specifically that @Scripts.Render("~/bundles/jquery")appears before @Scripts.Render("~/bundles/jqueryval"))

我遇到了同样的问题,解决方案实际上是确保脚本引用的顺序正确(特别是@Scripts.Render("~/bundles/jquery")之前出现的@Scripts.Render("~/bundles/jqueryval")

For some reason it wasn't like it by default when creating the new project and adding the nuget packages

出于某种原因,在创建新项目并添加 nuget 包时默认情况下不喜欢它

回答by C?t?lin R?doi

For me it was a little bit peculiar and counter-intuitive.

对我来说,这有点奇怪和违反直觉。

The page was displayed from the controller with a custom route attribute:

该页面是从具有自定义路由属性的控制器显示的:

[Route("contact")]
[HttpGet]
public ActionResult Contact()
{
    return this.View();
}

but the POST action handling the AjaxRequest had no [Route("contact")] attribute and that's why it didn't work.

但是处理 AjaxRequest 的 POST 操作没有 [Route("contact")] 属性,这就是它不起作用的原因。