栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

将复选框列表传递到视图中,并拉出IEnumerable [重复]

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

将复选框列表传递到视图中,并拉出IEnumerable [重复]

您不能使用

foreach
循环绑定到集合。您也不应该手动生成html,在这种情况下,由于未选中的复选框不会回发,因此无法正常工作。始终使用强类型的html帮助器,以便获得正确的双向模型绑定。

您尚未指示模型是什么,但是假设您有一个

User
并想要
Roles
为该用户选择,然后创建视图模型以表示您想要在视图中显示的内容

public class RoleVM{  public int ID { get; set; }  public string Name { get; set; }  public bool IsSelected { get; set; }}public class UserVM{  public UserVM()  {    Roles = new List<RoleVM>();  }  public int ID { get; set; }  public string Name { get; set; }  public List<RoleVM> Roles { get; set; }}

在GET方法中

public ActionResult Edit(int ID){  UserVM model = new UserVM();  // Get you User based on the ID and map properties to the view model  // including populating the Roles and setting their IsSelect property  // based on existing roles  return View(model);}

视图

@model UserVM@using(Html.BeginForm()){  @Html.HiddenFor(m => m.ID)  @Html.DisplayFor(m => m.Name)  for(int i = 0; i < Model.Roles.Count; i++)  {    @Html.HiddenFor(m => m.Roles[i].ID)    @Html.CheckBoxFor(m => m.Roles[i].IsSelected)    @Html.LabelFor(m => m.Roles[i].IsSelected, Model.Roles[i].Name)  }  <input type"submit" />}

然后在post方法中,将绑定您的模型,您可以检查已选择了哪些角色

[HttpPost]public ActionResult Edit(UserVM model){  // Loop through model.Roles and check the IsSelected property}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/576345.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号