I want to create a login form displayed in the sidebar on each page of my site. If the user enters the wrong user / pass, I want the errors to appear above this form (the rest of the remaining page was the same as before), and if he successfully logs in, I want the form to change to a list of user information (again, the rest of the page is the same as before logging in). I am using the MVC 3 web application project with the default internet application template. I have it:
_Layout.cshtml
@{ if (User.Identity.IsAuthenticated) { Html.RenderAction("ShowUserInfo", "User"); } else { Html.RenderAction("LogIn", "User"); } }
Usercontroller
[ChildActionOnly] public PartialViewResult ShowUserInfo() { // populate loggedInInfo from database based on // User.Identity.Name return PartialView("_LoggedInInfo", loggedInInfo); } private ActionResult RedirectToPrevious(string returnUrl) { if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\")) { return Redirect(returnUrl); } else { return RedirectToAction("index", ""); } } [ChildActionOnly] public PartialViewResult LogIn() { return PartialView("_LogInForm"); } // // POST: /User/LogIn [HttpPost] public ActionResult LogIn(LogInModel model, string returnUrl) { if (ModelState.IsValid) { if (Membership.ValidateUser(model.UserName, model.Password)) { FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe); return RedirectToPrevious(returnUrl); } else { ModelState.AddModelError("", "The user name or password provided is incorrect."); } } return RedirectToPrevious(returnUrl); }
_LogInForm
@model MyProject.Models.LogInModel <h2>Login</h2> <p> Please enter your username and password. @Html.ActionLink("Register", "register", "user") if you don't have an account.<br /> @Html.ValidationSummary(true, "Login was unsuccessful. Please correct the errors and try again.") </p> @using (Html.BeginForm("LogIn", "user")) { html stuff }
This works almost exactly as intended, except that if you enter the wrong username / password, the page simply reloads with an empty form and no error is displayed. I also tried some other things, but I either get errors about how I cannot pass the redirection from a partial view, or I get a partial view (with errors) that appears as a whole view, so it appears as a single whole page, separate from the rest of the site. If I log in correctly, everything works fine.
How can I correctly display errors above a form? I would prefer not to use Ajax or jQuery for this.