我有
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>
我的问题是,如果我像这样放置一个 foreach 循环
@foreach(var m in Model.ViewModel2)
{
<tr>
<td>@Html.CheckBoxFor(x => m.A) </td>
<td>@Html.CheckBoxFor(x => m.B) </td>
</tr>
}
问题在于,每个复选框都将具有相同的 id 和相同的名称属性,当然这不是有效的 html。
如何使它们没有 id 或具有 unquie id 和唯一名称属性?
我尝试做部分 View 和 display templates 两者都给我带来了同样的问题。
我唯一能想到的是
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>
}
但我认为这是一种可怕的做法。
最佳答案
使用 for
循环而不是 foreach
循环。
@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>
}
关于c# - 如何在asp.net mvc 3中制作不同的name属性名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5532188/