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

时间:2019-02-24 03:10:11

标签: c# asp.net razor modelstate validationsummary

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});
}

1 个答案:

答案 0 :(得分:1)

在使用ModelState错误时,应使用return View()而不是Redirect

At