Enumerated variables MVC2?

Ok, so I'm pretty new to model binding in MVC, and my question is this:

If I have a model with the IEnumerable property, how can I use the HtmlHelper with this so that I can present an Action that accepts this type of model.

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 snippet:

<%foreach(var subFoo in Model.SubFoo) { %>
     <label><%:subfoo.Omg %></label>
     <%=Html.TextBox("OH_NO_I'M_LOST") %>
<%} %>
+3
source share
1 answer

Instead IEnumerable<SubFoo>you can use an array:

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

And then, in your opinion:

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

Another option is to save IEnumerable<SubFoo>, but in this case you cannot use a strongly typed helper:

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

Source: https://habr.com/ru/post/1743191/


All Articles