I have an IEnumerable containing strings, using Data Annotations for validation:
[Required(ErrorMessage = "This is required.")]
[Remote("IsValid", "ControllerName")]
public IEnumerable<string> MyList { get; set; }
I’m then using this with an editor template. This is how I call it in my view:
@Html.EditorFor(m => m.MyList)
Finally, my template takes this IEnumarable and creates a number of form elements for each element:
@model IEnumerable<string>
@foreach (var str in Model)
{
<li>
@Html.LabelFor(m => str, "My Label")
@Html.TextBoxFor(m => str)
@Html.ValidationMessageFor(m => str)
</li>
}
Even though the form elements do render correctly, am I approaching this correctly? Also, I have noticed that it no longer validates. How can I resolve this?
You are going about it in a “correct” way. (Correct in that it can work, I have done this before) But with validation the reason I think it doens’t work is this, you have the validation on the IEnemerable and not on the string.
To get validation on each string. You would have to create a new model object say
And then where you have
public IEnumerable<string> MyList { get; set; }replace it withpublic IEnumerable<LabelString> MyList { get; set; }That should give you validation on each of the labels in the for loop.