我需要在主页上显示注册表和登录表.
为此,我在主页上使用子操作,如下所示:
@Html.Action("Register","Membership")
如果存在任何错误,它可以按预期完美地工作,因为它能够使用具有验证状态信息的适当模型重新呈现局部视图.
但是如果没有错误,当它尝试重定向时,它会抛出一个错误,指出:
Child actions are not allowed to perform redirect actions.
有没有办法解决?我确信有一种方法可以在主页上放置注册和登录表单.很可能我不知道,因为我是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); } } } }
主页’索引’视图:
@{ 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>
@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" /> }