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.

1 Answer 1

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>
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.