Moo*_*oon 6 asp.net-mvc razor asp.net-mvc-3 asp.net-mvc-2 child-actions
我需要在主页上显示注册表和登录表.
如果在这两个表单上验证失败,我需要在主页上显示正确的错误.
但如果没有错误,则必须将用户重定向到安全的仪表板.
为此,我child action
在主页上使用如下:
@Html.Action("Register", "Membership")
Run Code Online (Sandbox Code Playgroud)
它完全按预期工作,如果有任何错误,因为它能够re-render
在partial view
用正确的model
有validation state
信息.
但是如果没有错误,当它尝试重定向时,它会抛出一个错误,指出:
Child actions are not allowed to perform redirect actions.
Run Code Online (Sandbox Code Playgroud)
有没有办法解决?我确信有一种方法可以在主页上放置注册和登录表单.很可能我不知道,因为我是ASP .Net MVC的新手.
你能指点我在正确的方向吗?
一种方法是使用ajax表单作为登录和注册位,而不是在提交有效时返回RedirectResult,返回一些json,其中一些客户端脚本将注意并用于执行重定向为了你.
这是一个简化的例子.
控制器:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;
using MvcApplication12.Models;
namespace MvcApplication12.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Register()
{
return PartialView(new UserDetails());
}
[HttpPost]
public ActionResult Register(UserDetails details)
{
if (ModelState.IsValid)
{
return Json(new {redirect = true, url = Url.Action("Index","Dashboard")});
}
else
{
return PartialView(details);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
主页'索引'视图:
@{
ViewBag.Title = "Index";
}
<script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script type="text/javascript">
function checkForRedirect(data)
{
if (data.redirect && data.url)
{
location.href = data.url;
}
}
</script>
<p>Home page stuff.....</p>
<div id="RegistrationArea">
@Html.Action("Register")
</div>
<p> Home page stuff.....</p>
Run Code Online (Sandbox Code Playgroud)
注册表'注册'局部视图:
@model MvcApplication12.Models.UserDetails
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
@using (Ajax.BeginForm(new AjaxOptions()
{
HttpMethod = "POST",
Url = Url.Action("Register", "Home"),
OnSuccess = "checkForRedirect(data)",
UpdateTargetId = "RegistrationArea",
InsertionMode = InsertionMode.Replace
}))
{
@Html.LabelFor(m => m.UserName)
@Html.EditorFor(m => m.UserName)
@Html.ValidationMessageFor(m => m.UserName)
@Html.LabelFor(m => m.Password)
@Html.EditorFor(m => m.Password)
@Html.ValidationMessageFor(m => m.Password)
<input type="submit" />
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6487 次 |
最近记录: |