19

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?

devzero
  • 2,510
  • 4
  • 35
  • 55

2 Answers2

35

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").

eth0
  • 4,977
  • 3
  • 34
  • 48
  • 1
    How would you specifically add error to show up side by side with the error property? Say for example I have an editor template for the list item type and on that I have specified ValidationMessageFor that property... – Ε Г И І И О Sep 27 '12 at 12:54
  • 1
    Just set the key to be the property name, e.g. `ModelState.AddModelError("User.Password", "Invalid password");` – eth0 Oct 09 '12 at 16:13
  • 2
    Thanks! How to go about if the first property is a collection and I need to show the error next to a specific property of an arbitrary item. Will [] work here? – Ε Г И І И О Oct 09 '12 at 17:48
1

you can use for loop to set error in list. e.g.;

 for (int i = 0; i <mylist.Count(); i++)
 {
  if (dmylist[i].prop1== null)
     ModelState.AddModelError("dmylist[" + i + "].prop1", "prop1 is required.");
 }
Abhishek
  • 6,912
  • 14
  • 59
  • 85