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?
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 .
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.
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.
AddModelError(String, String) Adds the specified error message to the errors collection for the model-state dictionary that is associated with the specified key.
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")
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With