asp.net – CheckBoxList多个选择:难度模型绑定
发布时间:2020-12-15 19:44:27 所属栏目:asp.Net 来源:网络整理
导读:我正在上课,如下 public class UserRoleModel{ public string Role { get; set; } public bool UserRole { get; set; }} 和public UserRoleModel [] UserRoles {get;组; } 我的控制器如下: public ActionResult CreateUser() { UserDetailsModel model = ne
我正在上课,如下
public class UserRoleModel { public string Role { get; set; } public bool UserRole { get; set; } } 和public UserRoleModel [] UserRoles {get;组; } 我的控制器如下: public ActionResult CreateUser() { UserDetailsModel model = new UserDetailsModel(); return View(model); } [HttpPost] public ActionResult CreateUser(UserDetailsModel model) { return View(model); } 在我看来我有 >@foreach (var item in Model.UserRoles) { name = "UserRoles"+ ".Value["+ i + "]"; id= "UserRoles" + "_Value[" + i++ + "]"; selected = item.UserRole ? "checked="checked"" : ""; <p> <input type="checkbox" name="@name" id="@id" @selected value="true" /> <label for="@id">@item.Role</label> <input type="hidden" name="@name" value="false" /> </p> } 尽管我的看法中显示的值相应地显示,但是UserRoles没有模型绑定.我失踪了还是有更好更干净的方法? 解决方法
使用编辑器模板很好地实现了这些事情.他们也避免你在你的意见中写意大利面条代码.例:
模型: public class UserDetailsModel { public IEnumerable<UserRoleModel> Roles { get; set; } } public class UserRoleModel { public string Role { get; set; } public bool UserRole { get; set; } } 控制器: public class HomeController : Controller { public ActionResult Index() { return View(new UserDetailsModel { // Fill with some dummy stuff Roles = Enumerable.Range(1,5).Select(x => new UserRoleModel { Role = "role " + x,UserRole = false }) }); } [HttpPost] public ActionResult Index(UserDetailsModel model) { return View(model); } } 查看(?/ Views / Home / Index.cshtml): @model AppName.Models.UserDetailsModel @using (Html.BeginForm()) { @Html.EditorFor(x => x.Roles) <input type="submit" value="OK" /> } 编辑器模板(?/ Views / Home / EditorTemplates / UserRoleModel.cshtml): @model AppName.Models.UserRoleModel @Html.CheckBoxFor(x => x.UserRole) @Html.LabelFor(x => x.Role,Model.Role) @Html.HiddenFor(x => x.Role) 现在这就是我所说的干净的东西. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- owin和oAuth2.0之间的关系是什么?
- asp.net-mvc – 难以启动基本单元测试(样本来自我的书 – S
- asp.net-mvc – MVC ViewBag最佳实践
- asp.net – DNN vs Composite C1 – Pro and Cons
- asp.net-mvc – 应用程序不记录
- Razor页面在运行时无法在ASP.NET Core RC2中看到引用的类库
- ASP.NET MVC Route的几种配置方法
- 使用“正确的”.NET Framework版本
- asp.net – 如何调试Azure 500内部服务器错误[已关闭]
- asp.net-mvc-3 – aspnetdb.mdf来自我的ASP.NET MVC应用程序
推荐文章
站长推荐
- asp.net – 如何将演示模型与Webforms一起使用?
- 更改ASP.NET网站管理工具连接字符串
- asp.net – 使Windows身份验证和WKHTMLToPDF发挥
- asp.net – 在安全连接(HTTPS)中使用与SignalR的
- asp.net-mvc-3 – ASP.NET Web API问题 – 授权/
- asp.net-mvc – 如何在MVC视图中构造if语句
- asp.net-core – 如何从Microsoft.NetCore.App 2
- asp.net mvc中的用户登录验证过滤器
- asp.net – 麻烦与ajax POST调用WCF服务
- razor – 没有布局参考的ASP.NET默认MVC4应用程序
热点阅读