jQuery 为什么 Ajax.BeginForm 替换了我的整个页面?

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

Why does Ajax.BeginForm replace my whole page?

jqueryasp.net-mvc-3

提问by sydneyos

Context: Asp.Net MVC3 w/Razor

上下文:Asp.Net MVC3 w/Razor

I am trying to put a login form on a Razor layout (formerly master page) so that, when the user times out, s/he can be prompted to login without being redirected (as in RallyDev). So, I have created a partial _LogOn.cshtml with all the requisite stuff (username, etc.) inside an Ajax.BeginForm with an UpdateTargetId that points to a div that holds the logon controls inside the ajax form. The form posts back to the AccountsController.RefreshLogOn action, but obviously, the containing page may have been rendered from a different controller. The RefreshLogOn action returns PartialView("_LogOn"). In any case, my expectation/desire is that only the controls inside this div are replaced. What is happening instead is that my page location changes to /Accounts/RefreshLogon and the whole page is replaced by the partial. Is there another approach I should be taking?

我正在尝试将登录表单放在 Razor 布局(以前的母版页)上,以便当用户超时时,可以提示他/她登录而不被重定向(如在 RallyDev 中)。因此,我在 Ajax.BeginForm 中创建了一个部分 _LogOn.cshtml,其中包含所有必需的内容(用户名等),其中 UpdateTargetId 指向一个 div,该 div 包含 ajax 表单中的登录控件。表单回发到 AccountsController.RefreshLogOn 操作,但很明显,包含页面可能是从不同的控制器呈现的。RefreshLogOn 操作返回 PartialView("_LogOn")。无论如何,我的期望/愿望是只替换此 div 中的控件。相反发生的情况是我的页面位置更改为 /Accounts/RefreshLogon 并且整个页面被部分替换。

Here's the relevant code:

这是相关的代码:

_LogOn.cshtml

_LogOn.cshtml

 @{
        using (Ajax.BeginForm("RefreshLogOn", "Accounts", 
            new AjaxOptions { 
                      OnSuccess = "logonSucceeded", 
                      OnFailure = "logonFailed",         
                      HttpMethod = "Post", 
                      UpdateTargetId = "user-info" }, 
            new { @id = "refresh"}))
        {  
        @Html.AntiForgeryToken()

       <div id="user-info">
                <p>Your session has expired.</p>
            <div class="error">@Html.ValidationSummary()</div>
            <table>
                <tr>
                    <td>Username:</td>
                    <td>@Html.TextBoxFor(model => model.UserName)</td>
                </tr>
                <tr>
                    <td>Password:</td>
                    <td>@Html.PasswordFor(model => model.Password)</td>
                </tr>
                <tr>
                    <td>Remember Me:</td>
                    <td>@Html.CheckBoxFor(model => model.RememberMe)</td>
                </tr>

            </table>
        </div>
            }
        }

AccountsController

帐户控制器

public ActionResult RefreshLogOn (LogOnModel model)
{
    if (ModelState.IsValid)
    {
        if (MembershipService.ValidateUser(model.UserName, model.Password))
        {
            ...content elided...

            return PartialView("_LogOn");
        }

        ModelState.AddModelError("", ErrorMessages.IncorrectUsernameOrPassword);
    }

    return PartialView("_LogOn", model);
}

Ajax.BeginForm --> form tag generated:

Ajax.BeginForm --> 生成的表单标签:

<form action="/Accounts/RefreshLogOn" id="refresh" method="post" 
    onclick="Sys.Mvc.AsyncForm.handleClick(this, new Sys.UI.DomEvent(event));"
    onsubmit="Sys.Mvc.AsyncForm.handleSubmit(this, new Sys.UI.DomEvent(event), 
    { 
    insertionMode: Sys.Mvc.InsertionMode.replace, 
    httpMethod: &#39;Post&#39;, 
    updateTargetId: &#39;user-info&#39;, 
    onFailure: Function.createDelegate(this, logonFailed), 
    onSuccess: Function.createDelegate(this, logonSucceeded) 
    });">

回答by Darin Dimitrov

Ajax.*helpers in ASP.NET MVC 3 use unobtrusive jquery so make sure that you have referenced the jquery.unobtrusive-ajax.jsscript in your view. Also you could use FireBugto see what's happening under the scenes and why the form doesn't send an AJAX request.

Ajax.*ASP.NET MVC 3 中的助手使用不显眼的 jquery,因此请确保您已jquery.unobtrusive-ajax.js在视图中引用了该脚本。您也可以使用FireBug来查看场景下发生的事情以及表单不发送 AJAX 请求的原因。

Also the UpdateTargetId = "form"seems suspicious especially when your form has the refreshid: @id = "refresh". Is there some other element inside your DOM with id="form"? Maybe you meant UpdateTargetId = "refresh"?

UpdateTargetId = "form"似乎也很可疑,尤其是当您的表单具有refreshid: 时@id = "refresh"。您的 DOM 中是否还有其他元素id="form"?也许你的意思是UpdateTargetId = "refresh"

回答by shaijut

Note: my problem was first, i referenced wrongajax script file jquery.validate.unobtrusive.min.jsinstead of jquery.unobtrusive-ajax.jsand latest jquery version doesn't worked, onlyjquery-1.7.1.min.jsworked for me.

注意:我的问题首先是,我引用了错误的ajax 脚本文件jquery.validate.unobtrusive.min.js而不是jquery.unobtrusive-ajax.js最新的 jquery 版本不起作用,jquery-1.7.1.min.js对我有用。

i was tryingto return content after successful entry

试图在成功进入后返回内容

so here is the order:

所以这是顺序:

<script src="~/js/jquery-1.7.1.min.js"></script>
<script src="~/js/jquery.validate.min.js"></script>
<script src="~/js/jquery.unobtrusive-ajax.min.js"></script>

Post of Darinand Richard Everetthelped. hope helps.

DarinRichard Everett 的职位提供了帮助。希望有所帮助。

回答by Ivan Sokalskiy

I had the same problem and solution was:

我遇到了同样的问题,解决方案是:

  • Check that UnobtrusiveJavaScriptEnabled is true.
  • Add reference to jquery.unobtrusive-ajax.js as Darin adviced.
  • 检查 UnobtrusiveJavaScriptEnabled 是否为真。
  • 按照 Darin 的建议添加对 jquery.unobtrusive-ajax.js 的引用。

Unfortunatelly, it will not help for you because you set UnobtrusiveJavaScriptEnabled to false, but can help for somebody.

不幸的是,它对您没有帮助,因为您将 UnobtrusiveJavaScriptEnabled 设置为 false,但可以帮助某人。

回答by dis.iz.peez

Late but correct. Make sure to reference the unobtrusive-ajax.js file as well as the MicrosoftAjax.js and MicrosoftMvcAjax.js files in that order. Works

迟到但正确。确保按顺序引用 unobtrusive-ajax.js 文件以及 MicrosoftAjax.js 和 MicrosoftMvcAjax.js 文件。作品

回答by Ronen Festinger

Notice if you use Asp.Net template like I do, It bundles the file to bundles/jqueryval. So you have to add

请注意,如果您像我一样使用 Asp.Net 模板,它会将文件捆绑到 bundles/jqueryval。所以你必须添加

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

to the page.

到页面。

回答by bubbassauro

Besides checking if the .js is referenced, also check if no other form tags are being rendered. In my case, I had another form tag on the master page with the default action that was causing the whole page to reload.

除了检查 .js 是否被引用,还要检查是否没有其他表单标签被渲染。就我而言,我在母版页上有另一个表单标记,其默认操作会导致整个页面重新加载。