jQuery MVC 4 Ajax.beginform 提交 - 导致完全回发
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15253692/
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
MVC 4 Ajax.beginform submit - causes full postback
提问by Joe
MVC4 Internet project
MVC4互联网项目
I'm using Ajax.BeginForm to do a Postback with validation and it posts back the entire page rather than just the UpdateTargetID. I've looked at other posts on SO and haven't found the answer. I've built a new MVC4 Internet project just for testing (VS 2012 has been updated with 'ASP.NET and Web Tools 2012.2').
我正在使用 Ajax.BeginForm 进行带有验证的回发,它回发整个页面而不仅仅是 UpdateTargetID。我已经看过关于 SO 的其他帖子,但没有找到答案。我已经构建了一个新的 MVC4 Internet 项目仅用于测试(VS 2012 已更新为“ASP.NET 和 Web 工具 2012.2”)。
Here's my code
这是我的代码
Controller
控制器
public ActionResult Index()
{
var vM = _db.Students.FirstOrDefault(); return View(vM);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(Student vM)
{
if (ModelState.IsValid)
{ //code if Model valid
return Json(new { url = Url.Action("About", "Controller") });
}
ModelState.AddModelError(string.Empty, "AJAX Post");
return PartialView("Index", vM);
}
View
看法
@model AJAX_Test.Models.Student
@{ ViewBag.Title = "Student"; }
<script src="~/Scripts/jquery-1.8.2.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<script type="text/javascript"> var onSuccess = function (result)
{
if (result.url) { window.location.href = result.url; }
}
// when server returns JSON object containing an url property redirect the browser </script>
<h1>@ViewBag.Title</h1>
<div id="IDXForm">
@using (Ajax.BeginForm("Index", new AjaxOptions() { UpdateTargetId = "IDXForm", OnSuccess = "onSuccess", HttpMethod = "Post" }))
{
@Html.AntiForgeryToken() @Html.ValidationSummary(true)
<span>@Html.EditorFor(m => m.FirstName) @Model.EnrollmentDate.ToShortDateString()</span> <input type="submit" value="Submit" />
}
</div>
The initial view is:
初步看法是:
After Submittal:
提交后:
Source code for body after submittal:
提交后正文的源代码:
<div id="body">
<section class="content-wrapper main-content clear-fix">
<script src="/Scripts/jquery-1.8.2.js"></script>
<script src="/Scripts/jquery.unobtrusive-ajax.js"></script>
<script type="text/javascript"> var onSuccess = function (result) { if (result.url) { window.location.href = result.url; } }
// when server returns JSON object containing an url property redirect the browser </script>
<h1>Student</h1>
<div id="IDXForm">
<form action="/" data-ajax="true" data-ajax-method="Post" data-ajax-mode="replace" data-ajax-success="onSuccess" data-ajax-update="#IDXForm" id="form0" method="post"><input name="__RequestVerificationToken" type="hidden" value="vkCszJu-fKT6zUr5ys2StOTPF6a9pZdj5k1MyaAZKo8MPweS53dUuni0C9B17NjL_GVydHa7-jI1H0F9HrYEdKxeCWq9mCeER3ebaZYLxIs1" /><span><input class="text-box single-line" id="FirstName" name="FirstName" type="text" value="Carson" /> 9/1/2005</span> <input type="submit" value="Submit" />
</form></div>
Can anyone see what is wrong with my code?
谁能看到我的代码有什么问题?
Thank you.
谢谢你。
回答by Darin Dimitrov
A couple of things that come to mind that might be causing this behavior:
想到可能导致这种行为的几件事:
In your question you have shown your bundle registrations but have you actually included them in your view or Layout? Make sure that in your view or layout you have first included
jquery.js
and thenjquery.unobtrusive-ajax.js
(in that order):@Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/jqueryval")
The
jquery.unobtrusive-ajax.js
script is not compatible with jquery 1.9 and later because it relies on the.live()
which has beenremoved in jQuery 1.9
. So if for some reason you have upgraded your jQuery version to 1.9 or later that won't work. You should downgrade.In your onSuccess callback you are redirecting to an url if the controller action returns a JSON. Have you verified that this is not the case? Because when a redirect happens using the
window.location.href
it's pretty normal that you get a full page reload and not a partial update
在您的问题中,您已经显示了您的捆绑注册,但您实际上是否将它们包含在您的视图或布局中?确保在您的视图或布局中首先包含
jquery.js
,然后jquery.unobtrusive-ajax.js
(按该顺序):@Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/jqueryval")
该
jquery.unobtrusive-ajax.js
脚本不使用jQuery 1.9和更高版本兼容,因为它依赖于.live()
这一直是removed in jQuery 1.9
。因此,如果由于某种原因您将 jQuery 版本升级到 1.9 或更高版本,那将不起作用。你应该降级。在您的 onSuccess 回调中,如果控制器操作返回 JSON,您将重定向到一个 url。您是否已确认情况并非如此?因为当使用重定向发生时
window.location.href
,您会重新加载整个页面而不是部分更新是很正常的
In all cases use a javascript debugging tool to see what exactly is happening. If you are using Firefox, then you could use FireBug. If you are using Google Chrome, you could use the Chrome Developer Toolbar. Look at the console for potential javascript errors you might have. Look at the network tab to see whether all javascripts are successfully loaded and you don't have 404 errors. Learn how to debug your javascript code with a tool. You will be surprised how much information about potential issues you might have with your code those tools will provide you.
在所有情况下,使用 javascript 调试工具查看到底发生了什么。如果您使用的是 Firefox,那么您可以使用 FireBug。如果您使用的是 Google Chrome,则可以使用 Chrome Developer Toolbar。查看控制台以了解您可能遇到的潜在 javascript 错误。查看网络选项卡以查看是否所有 javascript 都已成功加载并且您没有 404 错误。了解如何使用工具调试 javascript 代码。您会惊讶于这些工具将为您提供多少有关您的代码可能存在的潜在问题的信息。
回答by Joe
The contents of the UpdateTargetID must be in a partial view and that partial view needs to be called from the Controller Post Action. Darin answered me through e-mail (thank you Darin). You need to use a parital view. I've tried to update his answer twice and the moderators have not done it or provided an explanation why so I'm posting my own answer for others benefit.
UpdateTargetID 的内容必须在分部视图中,并且需要从 Controller Post Action 调用该分部视图。Darin 通过电子邮件回复了我(谢谢 Darin)。您需要使用对等视图。我已经尝试两次更新他的答案,但版主没有这样做或提供解释原因,所以我发布了我自己的答案以供其他人使用。
_MyForm View:
_MyForm 视图:
@model AJAX_Test.Models.Student
@using (Ajax.BeginForm("Index", new AjaxOptions { UpdateTargetId = "IDXForm", OnSuccess = "onSuccess" }))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<span>
@Html.EditorFor(m => m.FirstName) @Model.EnrollmentDate.ToShortDateString()
</span>
<input type="submit" value="Submit" />
}
Main View :
主视图:
<div id="IDXForm">
@Html.Partial("_MyForm")
</div>
Controller Post Action:
控制器发布操作:
ModelState.AddModelError(string.Empty, "AJAX Post");
return PartialView("_MyForm", vM);
回答by JenonD
Couple of other things to note.
还有一些需要注意的事情。
- jquery.unobtrusive-ajax.js now supports JQuery 1.9. I have installed jquery.unobtrusive-ajax.js version 3.0.0 and it is working with JQuery 1.9
- jquery.unobtrusive-ajax.js 现在支持 JQuery 1.9。我已经安装了 jquery.unobtrusive-ajax.js 版本 3.0.0 并且它正在使用 JQuery 1.9
2. Make sure all the div tages are closed properly, including the view which contains the Ajax.BeginForm and the main view. Also if you have @Html.Raw() in the main view or inside the view which contains Ajax.BeginForm be cautious about that too.
2. 确保所有 div 标签都正确关闭,包括包含 Ajax.BeginForm 的视图和主视图。此外,如果您在主视图或包含 Ajax.BeginForm 的视图中有 @Html.Raw() ,也要小心。
Posting here to save one day of head scratching.
在这里发帖以节省一天的头疼。
回答by juan
make sure you have your bundles config include this
确保你的 bundles 配置包括这个
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery.unobtrusive*",
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include( "~/Scripts/jquery.validate*"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include("~/Scripts/jquery.validate*"));
回答by Roopali Rawat
use:<script src="../Scripts/jquery.unobtrusive-ajax.js"></script>
用:<script src="../Scripts/jquery.unobtrusive-ajax.js"></script>
This JS is what makes Ajax work.
这个 JS 是让 Ajax 工作的原因。
回答by Ostati
At a minimum, you need these two includes:
至少,您需要这两个包括:
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")
And if that still does not help, check in web.config and make sure unobtrusive is enabled:
如果这仍然没有帮助,请检查 web.config 并确保启用了 unobtrusive:
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
And if that still has no effect, make sure unobtrusive js files are compatible with current jQuery version, whatever version of jQuery you are using, which can be found at a below URL:
如果仍然没有效果,请确保不显眼的 js 文件与当前的 jQuery 版本兼容,无论您使用的是什么版本的 jQuery,都可以在以下 URL 中找到: