2

I've got an inbound view model list, that has basically got four properties in.

public class Complaint
{
 public int Id { get; set;}
 public string Comments { get; set; }
 public int RuleId { get; set; }
 public int ResponseId { get; set; }
}

The data is coming through fine, and i can see it be bound to my List controller item.

Depending upon the data contained within RuleId, makes ResponseId and Comments have different validaton requirements. I'm looking to use ModelState.AddModelError to achieve this. In the past when I've had to do this form of validation, I had fixed field names on my View. But this application, I could have 6 groups, I could have 20. AddModelError takes the property name to associate the error with, as I mentioned I have a variable number of items in my list.

Does anyone know how I can loop over my List and know that the item I am inspecting, relates to a specific form field within my View?

foreach(var complaint in List<Complaint>)
{
 if (complaint.RuleId == 1) && (complaint.Comments == null)
 {
 ModelState.AddModelError("INDIVIDUAL PROPERTY NAME NEEDED", "error message");
 }
}

Thanks in advance

Tony

Ant P
25.3k8 gold badges74 silver badges109 bronze badges
asked Oct 11, 2014 at 8:51

1 Answer 1

2

Try (assuming model is List<Complaint>)

for(int i = 0; i < model.Count; i++)
{
 if (model[i].RuleId == 1) && (model[i].Comments == null)
 {
 string propertyName = string.Format("[{0}].Comments", i); // returns "[0].Comments", "[1].Comments" etc
 ModelState.AddModelError(propertyName , "error message");
 }
}

This assumes you are generating your controls in the view using a for loop or custom EditorTemplate for Complaint.cs

answered Oct 11, 2014 at 9:07
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Stephen. That worked perfectly. Can't believe I didn't try that. I was looking for some sort of object that would contain it!

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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