This question has been asked many times but I don’t think the way I need it.
I’m trying to implement a login form on the home page but this form is located in a section that pops up, like you have on this site: http://myanimelist.net.
I’ve created a partial view for my login form:
@model ArtWebShop.Models.customers
@section Validation {
@Scripts.Render("~/bundles/jqueryval")
}
<section id="login">
@using (Html.BeginForm("LoginValidate", "Login", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.ValidationSummary(true)
@Html.ValidationSummary()
<fieldset>
<legend>Login</legend>
@Html.LabelFor(model => model.email)
@Html.TextBoxFor(m => m.email)
@Html.LabelFor(m => m.password)
@Html.PasswordFor(m => m.password)
<input type="submit" value="Login" class="button" />
</fieldset>
}
</section>
This is shown on the home page (index.cshtml):
<section class="shown">
@Html.Partial("_LoginPartial")
@Html.ValidationSummary(true)
@Html.ValidationSummary()
</section>
The partial view is shown correctly.
But now comes the part that doesn’t work.
When you press login if you haven’t filled in the fields, the validation is done in my LoginController as it should but I can’t seem the send the errors to my home page view when I redirect.
[HttpPost]
public ActionResult LoginValidate(string redirect)
{
if (_unitOfWork.CustomersRepository.CostumerIsValid(Request.Form["email"], Request.Form["password"]))
{
if (!String.IsNullOrEmpty(redirect) || String.Compare(redirect, "none", StringComparison.OrdinalIgnoreCase) == 0)
{
if (redirect != null) Response.Redirect(redirect, true);
}
else
{
return RedirectToAction("index", "Home");
}
}
ModelState.AddModelError("email", "You entered an incorrect email address");
ModelState.AddModelError("password", "You entered an invalid password");
return RedirectToAction("index", "Home");
}
That’s my loginValidation. Since nothing is filled in the errors are added to the ModelState and then it redirects to the home page. This however doesn’t shows me the errors.I’m guessing it’s exactly because I redirect but how can I solve this?
You can use TempDataDictionary to store the ModelStateDictionary between redirects.
In your LoginValidate action you would store the ModelState like so:
And in your HomeController, Index action you would check if the TempData has a ModelState:
You could make this a little bit cleaner by using custom action filters; see this blog, number 13.