我有一个Menusettings页面,显示数据库中的所有menuname(Menutable)。我想将所有细节保存到MenuRole表中。为此我想我必须迭代每个menuitem并将详细信息存储在MenuRole表中(这是正确的方法吗?)。但问题是我得到MenuList为null.So我无法迭代menulist。我也不知道如何将checkbox值绑定到MenuRole表。
视图
型号
public class MenuRoleVM
{
public int? RoleId { get; set; }
public SelectList RoleList { get; set; }
public MenuRole MenuRole { get; set; }
public IEnumerable<Menu> MenuList { get; set; }
}
public partial class MenuRole
{
public int Id { get; set; }
public Nullable<int> MenuID { get; set; }
public Nullable<int> RoleID { get; set; }
public Nullable<System.DateTime> TransactionTime { get; set; }
public bool CanAdd { get; set; }
public bool CanEdit { get; set; }
public bool CanDelete { get; set; }
public bool CanView { get; set; }
public virtual Menu Menu { get; set; }
public virtual Role Role { get; set; }
}
public partial class Menu
{
public Menu()
{
this.MenuRoles = new HashSet<MenuRole>();
}
public int Id { get; set; }
public string MenuName { get; set; }
public string NavigateUrl { get; set; }
public Nullable<int> ParentID { get; set; }
public virtual ICollection<MenuRole> MenuRoles { get; set; }
}
用于绑定视图的控制器
public ActionResult Add()
{
var _menuRoleVM = new MenuRoleVM
{
RoleList = new SelectList(_db.Roles.ToList(), "Id", "RoleName"),
MenuList = _db.Menus.Where(m => m.NavigateUrl != "#"),
MenuRole = new MenuRole()
};
return View(_menuRoleVM);
}
HTML标记视图
@model SMS.Models.ViewModel.MenuRoleVM
@foreach (var item in Model.MenuList.Select((x, i) => new { Data = x, Index = i }))
{
<tr>
<td>
<input type="checkbox" class="minimal checkAll" />
</td>
<td>@item.Data.MenuName</td>
<td>
@Html.CheckBoxFor(m => m.MenuRole.CanAdd, new { @class = "minimal single" })
</td>
<td>
@Html.CheckBoxFor(m => m.MenuRole.CanEdit, new { @class = "minimal single" })
</td>
<td>
@Html.CheckBoxFor(m => m.MenuRole.CanDelete, new { @class = "minimal single" })
</td>
<td>
@Html.CheckBoxFor(m => m.MenuRole.CanView, new { @class = "minimal single" })
</td>
</tr>
}
非常感谢任何帮助?
答案 0 :(得分:1)
您需要具有代表您要显示/编辑内容的视图模型
public class MenuVM
{
public int ID { get; set; }
public string Name { get; set; }
public bool CanAdd { get; set; }
public bool CanEdit { get; set; }
public bool CanDelete { get; set; }
public bool CanView { get; set; }
}
public class MenuRoleVM
{
public int? RoleId { get; set; }
public SelectList RoleList { get; set; }
public List<MenuVM> MenuList { get; set; }
}
并在视图中
@model MenuRoleVM
@using (Html.BeginForm())
{
@Html.DropDownListFor(m => m.RoleId, Model.RoleList)
for(int i = 0; i < Model.MenuList.Count; i++)
{
@Html.HiddenFor(m => m.MenuList[i].ID)
@Html.DisplayFor(m => m.MenuList[i].Name)
@Html.CheckBoxFor(m => m.MenuList[i].CanAdd)
@Html.CheckBoxFor(m => m.MenuList[i].CanEdit)
....
}
<input type="submit" ... />
}