netwire
netwire

Reputation: 7225

Html.LabelFor inside a loop

I have the following code:

<% foreach (var orderDetail in Model.OrderDetails) { %>
    <div><%= Html.LabelFor( x => orderDetail.DateOfBirth)%></div>
    <div><%= Html.TextBoxFor(x => orderDetail.DateOfBirth) %></div>
<% } %>

The info is being displayed, however, I can't click on the label and go to the text box because the ID attribute is being repeated due to the foreach loop.

<label for="orderDetail_DateOfBirth">DateOfBirth</label>
<input type="text" value="" name="orderDetail.DateOfBirth" id="orderDetail_DateOfBirth">

Does anyone know how to fix this?

UPDATE:

I ended up doing it this way since UpdateModel() didn't work either, any thoughts?

<% 
    int i = 0;
    foreach (var orderDetail in Model.OrderDetails) { %>

        <div><label for="DateOfBirth_<%=i %>_">Date of Birth</label></div>
        <div><%= Html.TextBox("DateOfBirth[" + i + "]", orderDetail.DateOfBirth) %></div>

<% i++
   } %>

Upvotes: 2

Views: 1724

Answers (2)

Patricia
Patricia

Reputation: 7802

have a look at this post from phil haack

http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx

near the bottom of the article it talks about looping controls and using array indexes and whatnot.

Here's the basic syntax taken from there and adjusted to fit your senario.

<% for (int i = 0; i < Model.OrderDetails.count; i++) { %>

  <%: Html.LabelForm(m =>  Model.OrderDetails[i].DateOfBirth) %>
  <%: Html.TextBoxFor(m => Model.OrderDetails[i].DateOfBirth) %>

<% } %>

for the model binder to handle this properly it has to have sequential indexes. But other then that, this should work.

Upvotes: 3

cpoDesign
cpoDesign

Reputation: 9153

You can create custom id inside of the loop

i would use htmlAttributes to define the id. Such as:

<%
        int i = 0;
        foreach (var orderDetail in Model.OrderDetails) { 

           %>

    <div><%= Html.LabelFor( x => orderDetail.DateOfBirth)%></div>
    <div><%= Html.TextBoxFor(x => orderDetail.DateOfBirth, new { id = "orderDetailDateOfBirth_" + i++ })%></div>
<% } %>

Or you can use :

jquery to identify object that you had clicked on using $(this)

Upvotes: 0

Related Questions