asp.net-mvc – MVC3如何在ViewModel中将多个复选框绑定到1个属
发布时间:2020-12-16 04:19:21 所属栏目:asp.Net 来源:网络整理
导读:我需要显示一个复选框列表,可以检查多个复选框. 当用户点击提交时,这些复选框的值需要进入ViewModel中的属性…这是我到目前为止所得到的… public class RegisterModel{ public Liststring Roles { get; set; } public ListRoleModel SelectedRoles { get; s
我需要显示一个复选框列表,可以检查多个复选框.
当用户点击提交时,这些复选框的值需要进入ViewModel中的属性…这是我到目前为止所得到的… public class RegisterModel { public List<string> Roles { get; set; } public List<RoleModel> SelectedRoles { get; set; } } public class RoleModel { public string RoleName { get; set; } } 在视图中我试图这样做…… @foreach (var role in Model.Roles) { @Html.CheckBoxFor(m => m.SelectedRoles,role.RoleName)@role.RoleName } 我收到以下错误: CS0029: Cannot implicitly convert type 'System.Collections.Generic.List<string>' to 'bool' 有人能告诉我我做错了什么吗? 解决方法
简单:调整视图模型以匹配您的视图要求(显示某些角色的复选框列表),使用编辑器模板并避免在视图中编写循环.
所以: 查看型号: public class RegisterModel { public List<RoleModel> Roles { get; set; } } public class RoleModel { public string RoleName { get; set; } public bool Selected { get; set; } } 控制器: public class HomeController : Controller { public ActionResult Index() { var model = new RegisterModel { Roles = new[] { new RoleModel { RoleName = "administrator" },new RoleModel { RoleName = "developer" },new RoleModel { RoleName = "janitor :-)" },}.ToList() }; return View(model); } [HttpPost] public ActionResult Index(RegisterModel model) { // at this stage the model will contain all the // information you need return View(model); } } 查看(?/ Views / Home / Index.cshtml): @model RegisterModel @using (Html.BeginForm()) { @Html.EditorFor(x => x.Roles) <button type="submit">OK</button> } 编辑模板(?/ Views / Home / EditorTemplates / RoleModel.cshtml): @model RoleModel <div> @Html.HiddenFor(x => x.RoleName) @Html.CheckBoxFor(x => x.Selected) @Html.LabelFor(x => x.Selected,Model.RoleName) </div> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- VS2017中使用组合项目_windows服务+winform管理_项目发布_测
- asp.net – AWS对象失效 – /如何确保从Edge中删除图像
- 在ASP.NET中清除FileUpload内容
- 日志记录 – 如何在ASP.NET MVC 6中注册ILogger进行注入
- asp.net – JQGrid不显示数据
- 在ASP.NET 2.0中的特定时间清除缓存
- asp.net – GetExternalLoginInfo在Google OWIN提供程序上返
- ASP.NET Core Identity获取用户id
- asp.net-mvc – 更改表中给定行的背景颜色
- asp.net-mvc – Web API 2需要使用尾部斜杠来使自定义属性路
推荐文章
站长推荐
热点阅读