我在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>
}
现在,我要在“编辑”模式下选中复选框列表。 在控制器的编辑模式下,我编写了以下代码:
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 + ",");
}
}
我希望复选框列表在“编辑模式”下被选中。
答案 0 :(得分:0)
将您的复选框代码替换为以下代码。
@ Html.CheckBoxFor(h => h.Hobbie,新的{@class =“ checkboxTwo”})