MVC5 Ajax.BeginForm refresh whole page

南楼画角 提交于 2019-12-10 11:20:02

问题


Why is the form post not happening via ajax but instead is reloading to the new page?

My .js includes:

<script src="/App/JavaScript/Libraries/jquery-1.11.1-min.js"></script>
<script src="/App/JavaScript/Libraries/jquery.validate.js"></script>
<script src="/App/JavaScript/Libraries/jquery.validate.unobtrusive.js"></script>

My razor view:

<div id="login-partial-update">
@using (Ajax.BeginForm("Login",null, new AjaxOptions
{
    UpdateTargetId = "login-partial-update",
    HttpMethod = "POST"
}, new { id = "js-form-login" }))
{
    @Html.TextBoxFor(x => x.Email, new {placeholder = "Email address"})
    <div class="errormessage">
        @Html.ValidationMessageFor(x=>x.Email)
    </div>
    @Html.PasswordFor(x => x.Password, new {placeholder = "Password"})
    <div class="errormessage">
        @Html.ValidationMessageFor(x => x.Password)
    </div>
}
</div>

My controller code:

[HttpPost]
public ActionResult Login(LoginInputModel login)
{
     return PartialView("Widgets/Popups/_LoginInput", login);
}

Am I forgetting something?


回答1:


You have to include jquery.unobtrusive-ajax.js file in your view to make Ajax.BeginForm to work.




回答2:


This really tripped me up, and in searching for a solution - 99% of the responses all focused on previous versions of MVC and/or never mentioned the required NuGet packages. For some reason VS2013, does not include the "Microsoft jQuery Unobtrusive Ajax" package when it builds a default MVC project. I found that the "jQuery validation" package was not needed either.

Once I installed that package, and added the script references the results were returned correctly to the target DIV.

To confirm, I am using: - VS2013 with MVC 4.5.1 - jQuery 2.1.3 - Microsoft jQuery Unobtrusive Ajax 3.2.3

In BundleConfig.cs I decided to add a new bundle because of the confusion:

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

And then applied it to all pages by referencing it in _Layout.cshtml:

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



回答3:


Add this key code to webconfig file

 <appSettings>
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
 </appSettings>


来源:https://stackoverflow.com/questions/27242986/mvc5-ajax-beginform-refresh-whole-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!