2

I have

public class ViewModel1
{
   // some properties here
   public List<ViewModel2> ViewModel2 {get; set;}
}

public class ViewModel2
{
   public string A {get; set;}
   public string B {get; set;}
}

// view

<table>
  <thead>
     <tr> a </tr>
     <tr> b </tr>
  </thead>
   <tbody>
      // need to generate all ViewModel2 stuff in table row cell
   </tbody>
</table>

My problem is that if I put a foreach loop like this

@foreach(var m in Model.ViewModel2)
{
   <tr>
     <td>@Html.CheckBoxFor(x => m.A) </td>
     <td>@Html.CheckBoxFor(x => m.B) </td>
   </tr>
}

The problem with this each of these checkboxes will have the same id's and same name attribute what of course is not valid html.

How can I make them have either no id or a unquie id and unique name attribute?

I tried to do partial views and display templates both give me the same problem.

The only thing I can think of is

 int i = 0
    @foreach(var m in Model.ViewModel2)
    {
       <tr>
         <td>@Html.CheckBoxFor(x => m.A, new {@name = m.a + i}) </td>
         <td>@Html.CheckBoxFor(x => m.B) </td>
       </tr>
    }

But I think that is a horrible way to do it.

Community
  • 1
  • 1
chobo2
  • 83,322
  • 195
  • 530
  • 832

1 Answers1

3

Use a for loop not a foreach loop.

@for(int i = 0; i < Model.ViewModel2.Length; i++)
{
   <tr>
     <td>@Html.CheckBoxFor(x => x.ViewModel2[i].A) </td>
     <td>@Html.CheckBoxFor(x => x.ViewModel2[i].B) </td>
   </tr>
}
Eonasdan
  • 7,563
  • 8
  • 55
  • 82
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445