我是 MVC3 的新手,我不明白如何使用复选框。在我的模型中,我有一个服务列表和一个可用服务列表。这个想法是显示所有可用的服务,并让用户选择使用哪个服务,只需选中相应的复选框。
public Activity()
{
.....
this.Services = new List<Service>();
this.ServicesChecklist = new Dictionary<Service, bool>();
}
public virtual ICollection<Service> Services { get; set; }
public Dictionary<Service, bool> ServicesChecklist { get; set; }
我能够使用控制器私有字典AssignServiceToActivity(活动活动)的私有方法正确加载服务表
List<Service> s = new List<Service>(db.Services);
Dictionary<Service, bool> ServicesChecklist = new Dictionary<Service, bool>();
bool found;
foreach (var ser in s)
{
found = false;
foreach (var currService in activity.Services)
{
if (ser.id == currService.id)
{
ServicesChecklist.Add(ser, true);
found = true;
break;
}
}
if (!found)
ServicesChecklist.Add(ser, false);
}
return ServicesChecklist;
}
in my view I am trying to bind the checkboxes to the ServicesChecklist dictionary
<div id="tabs-2">
<table style="width:100%">
<tr>
<th>
Service
</th>
<th>
Type
</th>
<th>
Contact
</th>
<th>
Phone
</th>
</tr>
@foreach (var s in @Model.ServicesChecklist)
{
<tr>
<td>
@Html.CheckBox(s.Key.name, s.Key.id)
@Html.DisplayFor(modelItem => s.Key.name)
</td>
<td>
@Html.DisplayFor(modelItem => s.Key.ServiceType.name)
</td>
<td>
@Html.DisplayFor(modelItem => s.Key.contact_name)
</td>
<td>
@Html.DisplayFor(modelItem => s.Key.contact_phone)
</td>
</tr>
}
</table>
</div>
当页面加载但用户选择未保存在模型中时它工作正常
![enter image description here][1]
[1]: http://i.stack.imgur.com/Buklf.png