1

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"));
        }
    }
bigbyte
  • 119
  • 1
  • 10
  • Take a look at the generated html for `TextBoxFor(m => m.Username)` and see if your binding to the right control name – jamesSampica Jun 01 '18 at 17:55
  • Yes I am. The model data comes through fine. However, the modelstate is lost. – bigbyte Jun 01 '18 at 19:22
  • If `ModelState` is invalid, you return the view. Redirecting does not keep the values from `ModelState` (that is a property of the current controller) –  Jun 03 '18 at 01:10
  • But it's a partial view. If I return the view, it only renders the partial content, all content of the parent view is gone. – bigbyte Jun 04 '18 at 14:13
  • Is there a way I can set ModelState on HomeController/Index? Would "return HomeController.Index()" cause problems? – bigbyte Jun 05 '18 at 14:35

0 Answers0