1,在给一个layer弹出层做checkbox自动选中时,ViewBag传递的时object类型,用不了lambda表达式,代码如下,
1 @foreach (var perm in ViewBag.allPerms) 2 { 3 <input type="checkbox" id="permissionIds_@perm.Id" 4 name="PermissionIds" value="@perm.Id" 5 checked="@(ViewBag.RolePerms.Select(r=>r.Id).Contains(perm.Id))"/> 6 <label for="permissionIds_@perm.Id">@perm.Name</label> 7 }
2,于是在弹出层就不写foreach循环遍历checkbox,直接在点击编辑事件时的弹出层中 ‘添加层弹出后的成功回调方法success’ ,在里面通过ajax填充数据
Control中Edit方法获取数据
1 //填充角色数据并显示 2 public ActionResult Edit(long roleId = 0) 3 { 4 if (roleId == 0) 5 { 6 return Json(new JsonData { State = 0, ErrorMsg = "角色不存在!" }); 7 } 8 var role = RoleService.GetById(roleId); 9 if (role==null) 10 { 11 return Json(new JsonData { State = 0, ErrorMsg = "角色Id不存在!" }); 12 } 13 var allPerms = PermissionService.GetAll(); 14 var rolePerms = PermissionService.GetByRoleId(roleId); 15 RoleEditGetModel model = new RoleEditGetModel(); 16 model.RolePerms = rolePerms; 17 model.AllPerms = allPerms; 18 return Json(new JsonData { State = 1, Data = model }); 19 }
View中Layer弹出层success方法
1 success: function (layero, index) { 2 //填充数据 3 $.ajax({ 4 url: "/Role/Edit?roleId=" + id, 5 type: "post", 6 dataType: "json", 7 success: function (res) { 8 if (res.State == 1) { 9 var html = ""; 10 var bool = false; 11 for (var i = 0; i < res.Data.AllPerms.length; i++) { 12 bool = false; 13 for (var j = 0; j < res.Data.RolePerms.length; j++) { 14 if (res.Data.RolePerms[j].Id == res.Data.AllPerms[i].Id) { 15 bool = true; 16 break; 17 } 18 } 19 html += ' <input ' + (bool ? "checked" : "") + ' type="checkbox" id="permissionIds_' + res.Data.AllPerms[i].Id + '" name="PermissionIds" value="' + res.Data.AllPerms[i].Id + '" />
<label for="permissionIds_' + res.Data.AllPerms[i].Id + '">' + res.Data.AllPerms[i].Name + '</label>' 20 } 21 $("#formValue").html(html); 22 } 23 }, 24 error: function () { 25 layer.alert('网络请求失败!', { 26 title: '提示框', 27 icon: 0, 28 }); 29 } 30 }); 31 },