我在MVC中使用Checkbox我的CShtml是这样的:
List<registrationchk.Models.hobby> mylist1 = ViewBag.hobbies;
foreach (var h in mylist1)
{
<tr>
<input type="checkbox" name="hobbies" value="@h.Hobbie" class="checkboxTwo" style="background-color:aliceblue" />@h.Hobbie
</tr>
}
现在我想要在编辑模式下选中复选框列表。在Controller的编辑模式中我编写了这段代码:
public ActionResult Edit(int? id)
{
TestEntities db = new TestEntities();
ViewBag.hobbies = db.hobbies.ToList();
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Employee employee = db.Employees.Find(id);
string[] times = (employee.hobbies).Split(',');
// string hobbies = collection["hobbies"];
// collection["hobbies"] = string hobbies;
System.Text.StringBuilder sb = new System.Text.StringBuilder();
foreach (var item in employee.hobbies)
{
if (item)
{
//append each checked records into StringBuilder
sb.Append(item + ",");
}
}
我希望在编辑模式下检查复选框列表。
将您的复选框代码替换为以下代码。
@ Html.CheckBoxFor(h => h.Hobbie,new {@class =“checkboxTwo”})