MVC中CheckBoxList的3种实现方式
比如,当为一个用户设置角色的时候,角色通常以CheckBoxList的形式呈现。用户和角色是多对多关系:
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations; namespace MvcApplication2.Models
{
public class User
{
public int Id { get; set; } [Display(Name = "用户名")]
public string Name { get; set; } public IList<Role> Roles { get; set; }
}
} using System.Collections.Generic;
using System.ComponentModel.DataAnnotations; namespace MvcApplication2.Models
{
public class Role
{
public int Id { get; set; } [Display(Name = "角色名")]
public string Name { get; set; } public IList<User> Users { get; set; }
}
}
在界面中包括:用户的信息,所有角色,当前选中角色的Id。所以,与为用户设置角色界面对应的View Model大致这样:
using System.Collections.Generic; namespace MvcApplication2.Models
{
public class UserVm
{
public User User { get; set; }
public List<Role> AllRoles { get; set; }
public List<Role> UserRoles { get; set; }
public int[] SelectedRoleIds { get; set; }
}
}
HomeController中:
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using MvcApplication2.Models; namespace MvcApplication2.Controllers
{
public class HomeController : Controller
{
/// <summary>
/// 为用户设置初始角色Id
/// </summary>
/// <returns></returns>
public ActionResult Index()
{
UserVm userVm = new UserVm();
userVm.User = new User() {Id = 1, Name = "Darren"};
userVm.AllRoles = GetAllRoles();
userVm.SelectedRoleIds = new []{1, 4}; List<Role> currentUserRoles = new List<Role>();
foreach (var item in userVm.SelectedRoleIds)
{
var temp = GetAllRoles().Where(u => u.Id == item).FirstOrDefault();
currentUserRoles.Add(temp);
}
userVm.UserRoles = currentUserRoles;
return View(userVm);
} /// <summary>
/// 根据前端视图选择的角色Id,给UserVm的UserRoles属性重新赋值
/// </summary>
/// <param name="userVm"></param>
/// <returns></returns>
[HttpPost]
public ActionResult Index(UserVm userVm)
{
userVm.AllRoles = GetAllRoles(); List<Role> newUserRoles = new List<Role>();
foreach (var item in userVm.SelectedRoleIds)
{
var temp = GetAllRoles().Where(u => u.Id == item).FirstOrDefault();
newUserRoles.Add(temp);
}
userVm.UserRoles = newUserRoles;
return View(userVm);
} //获取所有的角色
private List<Role> GetAllRoles()
{
return new List<Role>()
{
new Role(){Id = 1, Name = "管理员"},
new Role(){Id = 2, Name = "库管员"},
new Role(){Id = 3, Name = "财务主管"},
new Role(){Id = 4, Name = "销售主管"},
new Role(){Id = 5, Name = "人力主管"}
};
}
}
}
方法一:通过在视图页编码的方式
@using MvcCheckBoxList.Model
@model MvcApplication2.Models.UserVm @{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
} @using (Html.BeginForm())
{
@Html.HiddenFor(m => m.User.Id) <br/>
@Html.LabelFor(m => m.User.Name)
@Html.EditorFor(m => m.User.Name)
@Html.ValidationMessageFor(m => m.User.Name)
<br/>
<ul style="list-style:none;">
@foreach (var a in Model.AllRoles)
{
<li>
@if (Model.SelectedRoleIds.Contains(a.Id))
{
<input type="checkbox" name="SelectedRoleIds" value="@a.Id" id="@a.Id" checked="checked"/>
<label for="@a.Id">@a.Name</label>
}
else
{
<input type="checkbox" name="SelectedRoleIds" value="@a.Id" id="@a.Id" />
<label for="@a.Id">@a.Name</label>
}
</li>
}
</ul>
<br/>
<input type="submit" value="为用户设置角色"/>
} @section scripts
{
@Scripts.Render("~/bundles/jqueryval")
}
效果如图:

方法二:通过NuGet的MvcCheckBoxList扩展
→工具--库程序包管理器--程序包管理器控制台
→install-package MvcCheckBoxList
@using MvcCheckBoxList.Model
@model MvcApplication2.Models.UserVm @{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
} @using (Html.BeginForm())
{
@Html.HiddenFor(m => m.User.Id) <br/>
@Html.LabelFor(m => m.User.Name)
@Html.EditorFor(m => m.User.Name)
@Html.ValidationMessageFor(m => m.User.Name)
<br/>
@Html.CheckBoxListFor(m => m.SelectedRoleIds,
m => m.AllRoles, //所有角色
r => r.Id, //value值
r => r.Name, //显示值
r => r.UserRoles, //用户当前角色
Position.Horizontal //CheckboxList排列方向
)
<br/>
<input type="submit" value="为用户设置角色"/>
} @section scripts
{
@Scripts.Render("~/bundles/jqueryval")
}
效果如图:

方法三:通过自定义扩展方法
MVC中CheckBoxList的3种实现方式的更多相关文章
- ASP.NET MVC 表单的几种提交方式
下面是总结一下在ASP.NET MVC中表单的几种提交方式. 1.Ajax提交表单 需要引用 <script type="text/javascript" src=" ...
- spring 整合 mybatis 中数据源的几种配置方式
因为spring 整合mybatis的过程中, 有好几种整合方式,尤其是数据源那块,经常看到不一样的配置方式,总感觉有点乱,所以今天有空总结下. 一.采用org.mybatis.spring.mapp ...
- Django中提供的6种缓存方式
由于Django是动态网站,所有每次请求均会去数据进行相应的操作,当程序访问量大时,耗时必然会更加明显,最简单解决方式是使用: 缓存,缓存将一个某个views的返回值保存至内存或者memcache中, ...
- 【温故知新】——原生js中常用的四种循环方式
一.引言 本文主要是利用一个例子,讲一下原生js中常用的四种循环方式的使用与区别: 实现效果: 在网页中弹出框输入0 网页输出“欢迎下次光临” 在网页中弹出框输入1 网页输出“查询中……” 在 ...
- Springboot中IDE支持两种打包方式,即jar包和war包
Springboot中IDE支持两种打包方式,即jar包和war包 打包之前修改pom.xml中的packaging节点,改为jar或者war 在项目的根目录执行maven 命令clean pa ...
- JAVA高级架构师基础功:Spring中AOP的两种代理方式:动态代理和CGLIB详解
在spring框架中使用了两种代理方式: 1.JDK自带的动态代理. 2.Spring框架自己提供的CGLIB的方式. 这两种也是Spring框架核心AOP的基础. 在详细讲解上述提到的动态代理和CG ...
- Vue中常用的几种传值方式
Vue中常用的几种传值方式 1. 父传子 父传子的实现方式就是通过props属性,子组件通过props属性接收从父组件传过来的值,而父组件传值的时候使用 v-bind 将子组件中预留的变量名绑定为da ...
- MVC中处理表单提交的方式(Ajax+Jquery)
MVC中处理表单有很多种方法,这里说到第一种方式:Ajax+Jquery 先看下表单: <form class="row form-body form-horizontal m-t&q ...
- MVC中实现Area几种方法
概述 ASP.NET MVC中,是依靠某些文件夹以及类的固定命名规则去组织model实体层,views视图层和控制层的.如果是大规模的应用程序,经常会由不同功能的模块组成,而每个功能模块 ...
随机推荐
- Java 泛型和类型安全的容器
使用java SE5之前的容器的一个主要问题就是编译器允许你向容器插入不正确的类型,例如: //: holding/ApplesAndOrangesWithoutGenerics.java // Si ...
- hdu 3951 硬币围成一圈(博弈)
n个硬币围成一个环 每次只能取1-K个硬币 最后取完者胜 假如5个硬币 每次取1-2个情况1 先手取1个 后手取剩下4个中间2个 破坏了连续 虽然最后剩2个,但先手只能取一个 然后后再取一个 后手胜 ...
- HBase(一)HBase入门简介
一 HBase 的起源 HBase 的原型是 Google 的 BigTable 论文,受到了该论文思想的启发,目前作为 Hadoop 的子项目来开发维护,用于支持结构化的数据存储. Apache H ...
- 【58沈剑架构系列】微服务架构之RPC-client序列化细节
第一章聊了[“为什么要进行服务化,服务化究竟解决什么问题”] 第二章聊了[“微服务的服务粒度选型”] 上一篇聊了[“为什么说要搞定微服务架构,先搞定RPC框架?”] 通过上篇文章的介绍,知道了要实施微 ...
- USACO 6.5 All Latin Squares
All Latin Squares A square arrangement of numbers 1 2 3 4 5 2 1 4 5 3 3 4 5 1 2 4 5 2 3 1 5 3 1 2 4 ...
- loadrunner运行时设置中清空缓存方法
用函数web_cache_clearup()或run-time settings---browser emulation 把clear cache on each iteration打勾 W v\] ...
- poj1730 - Perfect Pth Powers(完全平方数)(水题)
/* 以前做的一道水题,再做精度控制又出了错///... */ 题目大意: 求最大完全平方数,一个数b(不超过int范围),n=b^p,使得给定n,p最大: 题目给你一个数n,求p : 解题思路: 不 ...
- C#拖拽操作
C#的拖拽 本文将以Winform为例 有两个主要的事件: DragEnter 拖拽到区域中触发的事件 DragDrop 当拖拽落下的时候出发此事件 饮水思源 参考博客: http://www.cnb ...
- [leetcode greedy]134. Gas Station
There are N gas stations along a circular route, where the amount of gas at station i is gas[i]. You ...
- Web应用扫描工具Wapiti
Web应用扫描工具Wapiti Wapiti是Kali Linux预置的一款Web应用扫描工具.该工具执行黑盒扫描,用户只需要输入要扫描的网址即可.该工具可以探测文件包含.数据库注入.XSS.CR ...