Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using EditorFor with IEnumerable<string> in MVC 3

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?

like image 557
Jonathan Avatar asked Aug 27 '12 02:08

Jonathan


1 Answers

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

public class LabelString
{
    [Required(ErrorMessage = "This is required.")]
    public string labelName { get; set; }
}

And then where you have public IEnumerable<string> MyList { get; set; } replace it with public IEnumerable<LabelString> MyList { get; set; }

That should give you validation on each of the labels in the for loop.

like image 194
AndyC Avatar answered Nov 09 '22 08:11

AndyC