I have a collection of ViewModels that I send back to from controller to the view
public class CourseTableViewModel
{
public string Prefix { get; set; }
public bool OwnerPremission { get; set; }
public bool AddPermission { get; set; }
public bool EditPermission { get; set; }
public bool DeletePermission { get; set; }
public bool ViewPermission { get; set; }
}
So I have a list of these
@foreach (var item in Model)
{
<tr>
<td>@Html.CheckBoxFor(x => item.OwnerPermission) </td>
//.... rest here //
</tr>
}
This will loop around X amount of times depending on how VM’s is being sent back but they all with have the same id and I want them different.
So I did this
<td>@Html.CheckBoxFor(x => item.OwnerPremission,new {@disabled = "disabled", @id = PermissionTypes.Owner.ToString() + counter})</td>
I am wondering if there is a better way.
Edit
So I did the template way(display not edit though) and have in it this
<td>@Html.CheckBoxFor(x => x.OwnerPremission, new { @disabled = "disabled"})</td>
It renders this for the first one.
<td><input type="checkbox" value="true" name="[0].OwnerPremission" disabled="disabled" checked="checked"><input type="hidden" value="false" name="[0].OwnerPremission"></td>
There is no id just name. Why does it not show up?
You could use an editor template for this view model which will ensure correct
idandnameattributes. So assuming your main view model is a collection of CourseTableViewModel or has a property that is a collection of CourseTableViewModel you could do the following in your main view:and in the corresponding editor template (
~/Views/Shared/EditorTemplates/CourseTableViewModel.cshtml):The editor template will be executed for each item in the view model collection and avoids you the need of writing any loops in your views. You just need to follow the naming conventions of those templates (it must be
called CourseTableViewModel.cshtmlbecause that’s the type name used in the main view model collection).UPDATE:
In the example I provided no id is being generated at all for the checkboxes. You could do the following to generate an unique id for each checkbox: