I’m having trouble with setting up some nested views in my MVC 3 architecture. This is what I currently have:
_Layout.cshtml
Logon.cshtml
Login.cshtml
ForgotPassword.cshtml
So basically, I have my _Layout.cshtml page that is just my master page. Then I have Logon.cshtml. This acts as my “master page” for my logon page. Under that, I have two partial views, Login.cshtml and ForgotPassword.cshtml. Behind all of this, I have a controller called AccountController. First, let me show you Logon.cshtml
Views/Account/Logon.cshtml
@model Coltrane.Web.Website.Models.Account.LogonViewModel
@{
Layout = "~/Views/Shared/_Layout.cshtml";
ViewBag.Title = "Logon";
}
@*@this.CssIncludes(@Url.Content("~/Content/login.css"))*@
@this.ScriptIncludes(@Url.Content("~/Content/scripts/Account/logon.js"))
@this.InitFunctionIncludes("lga_loginTabs.init()")
@this.InitFunctionIncludes("lga_formFocus.init()")
<div id="container">
<div class="sectionFocus noBg">
<div style="margin: 24px auto; width: 450px;">
<div class="customerLogo" style="margin: 24px auto;">
logo
</div>
<div id="tabContainer" style="position: relative; width:100%;">
<div id="login" class="box_c" style="position:absolute; width:100%;">
<h1>User Login</h1>
<div class="box_c_content">
<div class="sepH_c">
@{ Html.RenderAction("Login", "Account"); }
<a href="#" id="gotoFogot">Forgot your password?</a>
</div>
</div>
</div>
<div id="forgot" class="box_c" style="position: absolute; width:100%;display: none;">
<h1>Forgot Your Password?</h1>
<div class="box_c_content">
<div class="sepH_c">
@{ Html.RenderAction("ForgotPassword", "Account"); }
<a href="#" id="gotoLogin">Back to Login</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
Notice that I have render the Login and ForgotPassword partial views with Html.RenderAction. I’m doing this because each of these are actually forms and they need to post to the AccountController. Next, let me show you my Login.cshtml file:
Views/Account/Login.cshtml
@model Coltrane.Web.Website.Models.Account.LoginViewModel
@{
Layout = null;
}
@this.ScriptIncludes(@Url.Content("~/Content/scripts/Account/login.js"))
@this.InitFunctionIncludes("login.init()")
<div class="sepH_a">
<label>
Please enter your email and password to log into the system.</label>
</div>
@using (Html.BeginForm("Login", "Account", FormMethod.Post, new { id = "form_login" }))
{
<div class="sepH_a">
<div class="loginError">
@Html.ValidationSummary(true, "Login was unsuccessful. Please correct the errors and try again.")
@Html.ValidationMessageFor(m => m.UserName)<br />
@Html.ValidationMessageFor(m => m.Password)
</div>
</div>
<div class="sepH_a">
@Html.LabelFor(m => m.UserName, new { @class = "lbl_a" })
<br />
@Html.TextBoxFor(m => m.UserName, new { @class = "inpt_a_login", id = "lusername", name = "lusername" })
<span class="inputReqd" style="visibility: visible;">*</span>
</div>
<div class="sepH_a">
@Html.LabelFor(m => m.Password, new { @class = "lbl_a" })
<br />
@Html.PasswordFor(m => m.Password, new { @class = "inpt_a_login", id = "lpassword", name = "lpassword" })
<span class="inputReqd" style="visibility: visible;">*</span>
</div>
<div class="sepH_a">
@Html.CheckBoxFor(m => m.RememberMe, new { @class = "input_c", id = "remember" })
@Html.LabelFor(m => m.RememberMe, new { @class = "lbl_c" })
</div>
<div class="box_c_footer">
<button class="sectB btn_a" type="submit">
Login</button>
</div>
}
As you can see, this is just a simple form. One thing to note is that I’m, trying to use two models here. One for each of the views. One for the parent and one for both of the child views (forgotpassword has one as well). Anyways, let me show you my AccountController
Controllers/AccountController.cs
public class AccountController : Controller
{
private IAuthenticationService _authenticationService;
private ILoggingService _loggingService;
public AccountController(IAuthenticationService authenticationService,
ILoggingService loggingService)
{
_authenticationService = authenticationService;
_loggingService = loggingService;
}
public ActionResult Logon()
{
return View();
}
[HttpGet]
[ChildActionOnly]
public ActionResult Login()
{
return PartialView();
}
[HttpPost]
public ActionResult Login(LoginViewModel model, string returnUrl)
{
if (ModelState.IsValid)
{
if (Membership.ValidateUser(model.UserName, model.Password))
{
FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
&& !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
}
else
{
ModelState.AddModelError("", "An error has occurred.");
}
// If we got this far, something failed, redisplay form
return View("Logon");
// return View(model)
// return RedirectToAction("Index", "Home");
}
//........
}
On the method [HttpPost] Login(…), I’m checking to see if the user creds are correct. If so, everything works fine, but the issue is on an error. If I use return View("Logon"); I think I’m getting an infinite loop, if I use return View(model) I get the partial view for Login.cshtml, and if I use return RedirectToAction("Index", "Home");, I get returned to my logon view correctly, but my errors that I added do not show up (they do show up when i return View(model);. What am I doing wrong here? I think my setup makes sense, but I can’t figure out how to make it work correctly. I would like the return to render the Logon.cshtml view with the errors. Just to be complete, here are my two ViewModels for the provided Views:
public class LogonViewModel
{
}
public class LoginViewModel
{
[Required]
[Display(Name = "Email")]
public string UserName { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[Display(Name = "Remember Me?")]
public bool RememberMe { get; set; }
}
In my opinion the best way to handle this would be to redirect back to the index page. But as you mention, this causes your errors to be lost.
There is a nice solution for this though – save the model state in TempData and re-import it on the Index page. Here’s a link that provides a couple nice attributes you can use to make this pretty seamless:
[ImportModelStateFromTempData]and[ExportModelStateToTempData]http://weblogs.asp.net/rashid/archive/2009/04/01/asp-net-mvc-best-practices-part-1.aspx#prg