我正在使用部分视图进行登录,并希望在成功时将用户重定向到新页面,如果模型无效,则在部分视图中显示验证错误. ajax目标正在更新并成功或失败.如果模型有效,它将在更新目标中显示整个新页面,但我希望它重定向到新页面.我已经尝试过Redirect和RedirecttoAction,但它没有获得所需的结果.任何有关我可以去的想法都会获得ajax更新以重定向到新页面,而不是更新目标.另外,如果我使用错误的方法,请告诉我.
部分查看代码:
<% using (Ajax.BeginForm( "logon",null,new AjaxOptions { HttpMethod = "POST",UpdateTargetId = "SignInForm" },new { id = "SignInForm",ReturnUrl = Request.QueryString["ReturnUrl"] })) { %> <<Page HTML Controls>> <input type="submit" value="Log On" /> <% } %>
这是相关的控制器代码:
public ActionResult logon(logonModel model,string returnUrl) { if (ModelState.IsValid) { //Login Logic Code if (!String.IsNullOrEmpty(returnUrl)) { return Redirect(returnUrl); } else { return RedirectToAction("Index","App"); } } // If we got this far,something Failed,redisplay form if (Request.IsAjaxRequest()) return PartialView("logonControl"); return View(model); }
解决方法@H_404_12@
要执行重定向,您需要在客户端执行此操作.因此,您不能再使用UpdateTargetId,而应使用OnSuccess选项.您还需要修改logon控制器操作,以便在重定向的情况下测试它是否是ajax请求,并且在这种情况下返回一个带有重定向url的Json对象,该对象将在javascript中使用:
if (ModelState.IsValid)
{
if (string.IsNullOrEmpty(returnUrl))
{
returnUrl = Url.Action("Index","App");
}
if (Request.IsAjaxRequest())
{
return Json(new { returnUrl = returnUrl });
}
return Redirect(returnUrl);
}
在视图中:
<% using (Ajax.BeginForm(
"logon",new AjaxOptions {
HttpMethod = "POST",OnSuccess = "success"
},new {
id = "SignInForm",ReturnUrl = Request.QueryString["ReturnUrl"]
})) { %>
<<Page HTML Controls>>
<input type="submit" value="Log On" />
<% } %>
<script type="text/javascript">
function success(context) {
var returnUrl = context.get_data().returnUrl;
if (returnUrl) {
window.location.href = returnUrl;
} else {
// TODO: update the target form element with the returned partial html
}
}
</script>
if (ModelState.IsValid) { if (string.IsNullOrEmpty(returnUrl)) { returnUrl = Url.Action("Index","App"); } if (Request.IsAjaxRequest()) { return Json(new { returnUrl = returnUrl }); } return Redirect(returnUrl); }
在视图中:
<% using (Ajax.BeginForm( "logon",new AjaxOptions { HttpMethod = "POST",OnSuccess = "success" },new { id = "SignInForm",ReturnUrl = Request.QueryString["ReturnUrl"] })) { %> <<Page HTML Controls>> <input type="submit" value="Log On" /> <% } %> <script type="text/javascript"> function success(context) { var returnUrl = context.get_data().returnUrl; if (returnUrl) { window.location.href = returnUrl; } else { // TODO: update the target form element with the returned partial html } } </script>