我在同一个父视图中为两个不同的局部视图使用 ajax。ajax请求提交成功,调用了OnSuccess()函数,但是页面不会重定向。这是我的代码。我已经确定 returnurl 是一个绝对地址。看法:
@{
ViewBag.Title = "Log in/Register";
}
<hgroup class="title">
<h1>@ViewBag.Title.</h1>
</hgroup>
@section CustomScripts {
<script type ="text/javascript">
function OnSuccess(){
var returnUrl = @ViewBag.ReturnUrl
window.location = returnUrl
}
</script>
}
<section id="loginForm">
@{
if(!WebSecurity.IsAuthenticated){
<h2>Use a Creative Works account to log in.</h2>
@Html.Action("_LoginPartial", new {returnUrl = ViewBag.ReturnUrl })
}
}
</section>
<section id ="RegisterForm">
@{
if(!WebSecurity.IsAuthenticated){
<span>Don't have an account? Make one!</span>
@Html.Action("RegisterPartial", new { returnUrl = ViewBag.ReturnUrl })
}
}
</section>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
用于登录的部分视图:
@{
ViewBag.Title = "LoginPartial";
}
@using (Ajax.BeginForm("_LoginPartial", new {returnUrl = ViewBag.ReturnUrl},
new AjaxOptions(){UpdateTargetId = "loginForm",
InsertionMode = InsertionMode.Replace, OnSuccess = "OnSuccess"
})) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<legend>Log in Form</legend>
<ol>
<li>
@Html.LabelFor(m => m.UserName)
@Html.TextBoxFor(m => m.UserName)
@Html.ValidationMessageFor(m => m.UserName)
</li>
<li>
@Html.LabelFor(m => m.Password)
@Html.PasswordFor(m => m.Password)
@Html.ValidationMessageFor(m => m.Password)
</li>
<li>
@Html.CheckBoxFor(m => m.RememberMe)
@Html.LabelFor(m => m.RememberMe, new { @class = "checkbox" })
</li>
</ol>
<input type="submit" value="Log in" />
</fieldset>
}
和控制器:
[AllowAnonymous]
public ActionResult _LoginPartial(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
return PartialView(new LoginModel());
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult _LoginPartial(LoginModel model, string returnUrl)
{
if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
{
return PartialView();
}
// If we got this far, something failed, redisplay form
ModelState.AddModelError("", "The user name or password provided is incorrect.");
return PartialView(model);
}
编辑:父视图控制器
[AllowAnonymous]
[DisableCache]
public ActionResult Login(string returnUrl ="/")
{
var path = VirtualPathUtility.ToAbsolute(returnUrl);
var url = new Uri(Request.Url, path).AbsoluteUri;
ViewBag.ReturnUrl = url;
return View();
}