asp.net-mvc MVC 3 - Ajax.BeginForm 做一个完整的回发
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5061063/
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 3 - Ajax.BeginForm does a full post back
提问by Mike Barlow - BarDev
In the following code, I'm using Ajax.BeginForm to post data to the action asynchronously. The action gets called but the results are displayed to a new web page. I'v looked at a ton of example. This doesn't seem difficult. I've made the example extremely simple for a proof of concept (poc), but I'm still seeing a new page displayed.
在以下代码中,我使用 Ajax.BeginForm 将数据异步发布到操作。该操作被调用,但结果显示在新网页上。我看过很多例子。这似乎并不难。对于概念证明 (poc),我已经使示例变得非常简单,但我仍然看到显示了一个新页面。
Controller
控制器
[HttpPost]
[OutputCache(Location = OutputCacheLocation.None, NoStore = true)]
public string TestAjax(UserViewModel viewModel)
{
return viewModel.UserName;
}
View
看法
@model BasicMvc3Example2.Models.UserViewModel
@{
ViewBag.Title = "Index2";
Layout = null;//"~/Views/Shared/_Layout.cshtml";
}
<script src="/BasicMvc3Example2/Scripts/jquery-1.4.4.js" type="text/javascript"></script>
<script src="/BasicMvc3Example2/Scripts/jquery-ui.js" type="text/javascript"></script>
<script src="/BasicMvc3Example2/Scripts/jquery.validate.js" type="text/javascript"></script>
<script src="/BasicMvc3Example2/Scripts/jquery.validate.unobtrusive.js" type="text/javascript"></script>
<h2>Index2</h2>
<script type="text/javascript">
function PostFailure(){
alert("Failure");
}
function PostSuccess(){
alert("Success");
}
function PostOnComplete() {
alert("Complete");
}
</script>
Page Rendered: @DateTime.Now.ToLongTimeString()
@using (Ajax.BeginForm("TestAjax", new AjaxOptions { HttpMethod = "Post", UpdateTargetId = "textEntered", OnFailure = "PostFailure", OnSuccess = "PostSuccess", OnComplete = "PostOnComplete" }))
{
<div>
@Html.LabelFor(m => m.UserName)
@Html.TextBoxFor(m => m.UserName)
</div>
<div>
@Html.LabelFor(m => m.Password)
@Html.TextBoxFor(m => m.Password)
</div>
<div>
@Html.LabelFor(m => m.EmailAddress)
@Html.TextBoxFor(m => m.EmailAddress)
</div>
<input type="submit" id="submitForm" value="Submit Form" />
}
<div id="textEntered">d</div>
回答by Jeff Ogata
Can you check _Layout.cshtml
and make sure the ajax script is referenced? I don't think it is by default:
您可以检查_Layout.cshtml
并确保引用了 ajax 脚本吗?我不认为它是默认的:
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
回答by Mike Barlow - BarDev
Also remember that you need this in the webconfig
还要记住,你在 webconfig 中需要这个
<appSettings>
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>