Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add modelstate error to a list

I have a view that uses a list of modelitems like this:

List<It4You.AlertBrick.Library.Domain.Order.AbOrderLineItemPicked>

When I get this list serverside I check if this is one type of item, it has to have a valid serial number. If its another type I check if the user has put a checkmark in the "picked" checkbox. If both of these fails, I would like to add a modelstate error to this row. What is the best way of doing this?

like image 383
devzero Avatar asked Nov 18 '11 08:11

devzero


People also ask

How do I add an error message in ModelState?

Above, we added a custom error message using the ModelState. AddModelError() method. The ValidationSummary() method will automatically display all the error messages added into the ModelState .

How do I get ModelState error message in controller?

You can use SelectMany function c# to get error message from modelstate mvc. It will generate error message string it contains modelstate errors; we can return as json and display in html element. You have to define validations inside the class as per requirement.

How do I find ModelState errors in view?

To pass error to the view we can use ModelState. AddModelError method (if the error is Model field specific) or simply ViewBag or ViewData can also be used.

What is ModelState AddModelError?

AddModelError(String, String) Adds the specified error message to the errors collection for the model-state dictionary that is associated with the specified key.


1 Answers

You can quite simply add directly into ModelState as key/value pairs:

ModelState.AddModelError("error", "Serial is invalid");

and then in your view: @Html.ValidationMessage("error").

like image 117
eth0 Avatar answered Oct 05 '22 01:10

eth0