0

View

@model List<Dal.IAdministrator>

@Html.Partial("PartialCreateAdmin", new ViewModels.AdministratorCreateModel())

Partial

@model ViewModels.AdministratorCreateModel

@using (Html.BeginForm("Insert", "Admin", FormMethod.Post, new { }))
{
    <fieldset>
        <br />
        @Html.TextBoxFor(m => m.AccountName, new { placeholder = "Enter the account name here" })
        @if (!ViewData.ModelState.IsValid)
        {
            <p style="color: darkblue;"> @ViewData.ModelState["AccountName"].Errors[0].ErrorMessage </p> 
        }
    </fieldset>
    <br />

    <input type='Submit' value='Create' />
}

Controller:

    [HttpPost]
    public ActionResult Insert(AdministratorCreateModel vm)
    {
       // ...
        if(!accountNameExists)
        {
            ModelState.AddModelError("AccountName", "Account name does not exist, please try again!");
            return PartialView("PartialCreateAdmin", vm);
        }
        // ...
    }

Currently If the validation fails, it returns to the partial, but I want to return the view, with the message along the form? How can I do this?

Gerald Hughes
  • 5,771
  • 20
  • 73
  • 131
  • 1
    Can you trying `RedirectToAction`? `return PartialView` just returning partial view, you may create another action method returning view to display validation messages. – Tetsuya Yamamoto Jan 13 '17 at 09:12
  • @TetsuyaYamamoto yes, but how do I set the ModelState using RedirectToAction? – Gerald Hughes Jan 13 '17 at 09:15
  • IMO `ModelState` can't be accessed directly using `RedirectToAction`, however you can use `Session` property to set the message and return it into target view after redirection using viewmodel. – Tetsuya Yamamoto Jan 13 '17 at 09:22
  • @TetsuyaYamamoto `... if (!ModelState.IsValid) TempData["ViewData"] = ViewData; RedirectToAction( "Index" ); } public ActionResult Index() { if (TempData["ViewData"] != null) { ViewData = (ViewDataDictionary)TempData["ViewData"]; } ... }` – Gerald Hughes Jan 13 '17 at 09:23
  • 1
    Something like this may work: http://stackoverflow.com/questions/3363842/redirect-to-action-and-need-to-pass-data, due to POST-redirect-GET request sequence. – Tetsuya Yamamoto Jan 13 '17 at 09:25

0 Answers0