Our MVC3 model includes a collection of strings like this
[CannotBeEmpty(ErrorMessageResourceName = "ColorCodes", ErrorMessageResourceType = typeof(Resources.Strings))]
[Display(ResourceType = typeof(Resources.Strings), Name = "ColorCodes")]
public List<string> ColorCodes { get; set; }
I display this model in my View using
<div class="editor-field colors">
@Html.EditorFor(model => model.ColorCodes)
@Html.ValidationMessageFor(model => model.ColorCodes)
</div>
My problem is that myValidationMessageFor only renders 1 row while in the example below, the EditorFor reders 3 input fields.
<input class="text-box single-line" id="ColorCodes_0_" name="ColorCodes[0]" type="text" value="#d6c0d6">
<input class="text-box single-line" id="ColorCodes_1_" name="ColorCodes[1]" type="text" value="">
<input class="text-box single-line" id="ColorCodes_2_" name="ColorCodes[2]" type="text" value="#fcfcfc">
<span class="field-validation-valid" data-valmsg-for="ColorCodes" data-valmsg-replace="true"></span>
As you can see data-valmsg-for contains "ColorCodes" which is wrong. It should contain ColorCodes_0_, ColorCodes_1_ and ColorCodes_2_. How should I use the ValidationMessageFor when the model contains a Collection.
You can iterate model in for loop and receive expected result.
@for(int i = 0; i < Model.ColorCodes.Count; i++)
{
@Html.EditorFor(model => model.ColorCodes[i])
@Html.ValidationMessageFor(model => model.ColorCodes[i])
}
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