Dan
Dan

Reputation: 29365

MVC Html.ValidationMessage not firing on update

I'm having an issue where my validation messages are showing up fine on an add operation, but when it comes to the update page, the validation messages are not showing:

This is my action, IsValid is coming out as false, and action redirects to the edit view, but none of the validation messages are shown. Is there something wrong in my approach?

   [Authorize]
    public ActionResult UpdateCar(CarDTO car)
    {
        try
        {
            _carTask.Update(car); //required Name field not set
        }
        catch (RulesException ex)
        {
            ex.AddModelStateErrors(ModelState, null);
        }

        if (!ModelState.IsValid)
        {
            return RedirectToAction(ViewNames.EditCar, new {carKey = car.carKey});
        }
        return RedirectToAction(ViewNames.Home, new {carKey =   car.carKey});
    }


 <li>
    <label for="Name">Car Name:</label>
    <%= Html.TextBoxFor(x => x.Name, new { watermark="Car Name" })%>
      <br />
       <%= Html.ValidationMessage("Name") %>
 </li>

Upvotes: 1

Views: 1097

Answers (1)

David
David

Reputation: 15360

If the form is invalid then you are redirecting to a new page which will loose any modal error values you set. Instead just return the View. Haven't checked the syntax but something like the below.

if (!ModelState.IsValid)
{
    return View(ViewNames.EditCar, new {carKey = car.carKey});
}

return RedirectToAction(ViewNames.Home, new {carKey =   car.carKey});

Upvotes: 2

Related Questions