views:

277

answers:

1

Okay, so I'm fairly new to model binding in MVC, really, and my question is this:

If I have a model with an IEnumerable property, how do I use the HtmlHelper with that so I can submit to an Action that takes that model type.

Model Example:

public class FooModel {
    public IEnumerable<SubFoo> SubFoos { get; set; }
}
public class SubFoo {
    public string Omg { get; set; }
    public string Wee { get; set; }
}

View Snip:

<%foreach(var subFoo in Model.SubFoo) { %>
     <label><%:subfoo.Omg %></label>
     <%=Html.TextBox("OH_NO_I'M_LOST") %>
<%} %>
+2  A: 

Instead of IEnumerable<SubFoo> you could use an array:

public class FooModel {
    public SubFoo[] SubFoos { get; set; }
}

And then in your view:

<% for (var i = 0; i < Model.SubFoo.Length; i++) { %>
     <label><%:subfoo.Omg %></label>
     <%=Html.TextBoxFor(x => x.SubFoo[i].Omg) %>
<%} %>

Another possibility is to keep the IEnumerable<SubFoo> but in this case you cannot use the strongly typed helper:

<% for (var i = 0; i < Model.SubFoo.Count(); i++) { %>
     <label><%:subfoo.Omg %></label>
     <%=Html.TextBox("SubFoo[" + i + "].Omg") %>
<%} %>
Darin Dimitrov