0

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 Answer 1

1

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 });
        }
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.