chobo2
chobo2

Reputation: 85715

How to make different name attribute names in asp.net mvc 3?

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.

Upvotes: 2

Views: 1401

Answers (1)

Daniel A. White
Daniel A. White

Reputation: 190907

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>
}

Upvotes: 3

Related Questions