<tbody> <% foreach (var item in Model.GetDate) { %> <tr> <td> <input type="checkbox" name="chk" value="<%: item.ID %>" /> </td> <td> <%: item.PermissionModel.ModelName %> </td> <td> <%: item.Name %> </td> <td> <%: item.PerRoute %> </td> </tr> <% } %> </tbody>
以上是view里面写的
下面是controller里的勾选之后保存。那么我再次要添加checkbox选项的时候要把已经存入数据库里的取出来勾选到checkbox上,应该怎么写?
public ActionResult Permission() { var a = from p in db.PermissionItem orderby p.PermissionID select p; return View(a); } [HttpPost] public ActionResult Permission(FormCollection collection) { try { string[] values = Request.Form.GetValues("chk"); for (int i = 0; i < values.Count(); i++) { PermissionList model = new PermissionList() { PermissionID = Convert.ToInt32(values[i]), RoleID = Convert.ToInt32(Request.RequestContext.RouteData.Values["id"]) }; var a = db.PermissionList.Where(p => p.RoleID == model.RoleID && p.PermissionID == model.PermissionID); if (a.Count() <= 0) { db.PermissionList.InsertOnSubmit(model); } } db.SubmitChanges(); // TODO: Add insert logic here return RedirectToAction("Index"); } catch { return View(); } }
两种写法:
<input id="Remember" name="Remember" type="checkbox" value="@Model.Remember" />
或者
@Html.EditorFor(x => x.Remember)
将生成:
<input id="Remember" type="checkbox" value="true" name="Remember" /> <input type="hidden" value="false" name="Remember" />
要想知道更多,更详细的写法,看这:
http://gunnarpeipman.com/2013/06/better-solution-for-asp-net-mvc-checkbox-list/
我要从数据库读取我已经存放的ID把对应的checkbox进行勾选 应该怎么写?
var a = db.PermissionList.Where(p => p.RoleID == Convert.ToInt32(Request.RequestContext.RouteData.Values["id"])).Select(p => p.PermissionID).ToList();
var b = ""; if (a.Count > 0) { for (int i = 0; i < a.Count; i++) { b += a[i] + ","; } } ViewData["chk"] = b;
<%if(ViewData["chk"].ToString().Contains(item.ID.ToString())) {%>
<input type="checkbox" id="chk" name="chk" value="<%: item.ID %>" checked="checked" />
<%} %>
<%else {%>
<input type="checkbox" id="chk" name="chk" value="<%: item.ID %>" />
<%} %>