Search code examples
c#asp.netrazormodelstatevalidationsummary

Html.ValidationSummary Not Populating with Custom Errors ASP.NET MVC Razor Page


I'm fairly new to MVC, I need to create a custom error that would fire if the user does not select a category. However the Html.ValidationSummary is not populating when a product without categories is created. Instead the view is returned and shown on the browser without the validation summary being populated. Please see below, I've have copied the relevant code over.
CSHTML CODE

@Html.ValidationSummary(false, "", new { @class = "text-danger" })

CONTROLLER CODE

if (!model.HasCategories)
{
     ModelState.AddModelError(string.Empty, "A category is required.");
}

if(!ModelState.IsValid()) {
    return RedirectToAction("addEditProduct", new { id = model.P.ID});
}

Solution

  • when you are using ModelState errors you should use return View() instead of Redirect

        public ActionResult addEditProduct()
        {
            return View();
        }
    
        [HttpPost]
        public ActionResult addEditProduct(EditProductModel model)
        {
            if (!model.HasCategories)
            {
                ModelState.AddModelError(string.Empty, "A category is required.");
                return View(new { id = model.P.ID });
            }
    
            if (!ModelState.IsValid())
            {
                return View(new { id = model.P.ID });
            }
        }