I am unable to pass the model state errors from controller to the partial view.
I have index page with two partial views - sign up and log in. If sign up fails, I set a model error for Username property and redirect the browser to index with SignUpModel in TempData.
The model contents are communicated properly and I see the Username field pre-populated after failed effort. However, I do not see the error message.
The ViewData dictionary in index is empty. And the ModelState for the index is empty.
Main View
<h2>Sign Up</h2>
@Html.Partial("SignUp", TempData["SignUpModel"])
<h2>Sign In</h2>
@Html.Partial("Login", TempData["LoginModel"])
Sign Up
@model WebApp1.Models.SignUpModel
@using (Html.BeginForm("SignUp", "Account"))
{
<p>
@Html.TextBoxFor(m => m.Username)
@Html.ValidationMessageFor(m => m.Username)
</p>
<p>
@Html.PasswordFor(m => m.Password)
@Html.ValidationMessageFor(m => m.Password)
</p>
<button type="submit">Sign Up</button>
}
Controller
[HttpPost]
public ActionResult SignUp(Models.SignUpModel model)
{
if (ModelState.IsValid)
{
/* do something */
if (success)
{
/* do something */
return Redirect(Url.Action("Index", "Home"));
}
else
{
ModelState.AddModelError("Username", "SomeReason");
TempData["SignUpModel"] = model;
return Redirect(Url.Action("Index", "Home"));
}
}
else
{
TempData["SignUpModel"] = model;
return Redirect(Url.Action("Index", "Home"));
}
}