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视图层和控制层的.如果是大规模的应用程序,经常会由不同功能的模块组成,而每个功能模块 ...
随机推荐
- LeetCode699. Falling Squares
On an infinite number line (x-axis), we drop given squares in the order they are given. The i-th squ ...
- centos7 关闭默认firewalld,开启iptables
编者按: 对于使用了centos6系列系统N年的运维来说,在使用centos7的时候难免会遇到各种不适应.比如防火墙问题.本文主要记录怎么关闭默认的firewalld防火墙,重新启用iptables. ...
- 【LOJ】#2027. 「SHOI2016」黑暗前的幻想乡
题解 我一开始写的最小表示法写的插头dp,愉快地TLE成60分 然后我觉得我就去看正解了! 发现是容斥 + 矩阵树定理 矩阵树定理对于有重边的图只要邻接矩阵的边数设置a[u][v]表示u,v之间有几条 ...
- 在控制台连接oracle
Microsoft Windows [版本 6.1.7601]版权所有 (c) 2009 Microsoft Corporation.保留所有权利. C:\Users\lijt>sqlplus ...
- Redis在Window服务下的安装
Redis 安装 1.首先在Windows下下载安装Redis 下载地址:https://github.com/MicrosoftArchive/redis/releases 根据你电脑系统的实际情况 ...
- BZOJ3611 HEOI2014大工程
先建虚树,然后统计答案. 对于这个两点间最大值和最小值的操作我参考了hzwer的代码. 建虚树时注意判自环 By:大奕哥 #include<bits/stdc++.h> using nam ...
- Codeforces Round #489 (Div. 2)
A. Nastya and an Array time limit per test 1 second memory limit per test 256 megabytes input standa ...
- BZOJ.4316.小C的独立集(仙人掌 DP)
题目链接 \(Description\) 求一棵仙人掌的最大独立集. \(Solution\) 如果是树,那么 \(f[i][0/1]\) 表示当前点不取/取的最大独立集大小,直接DP即可,即 \(f ...
- [xsy3466]见面会
题意:有$n$个区间,把它们划分成若干段,如果一段$k$个区间的交长度$\geq2$,那么会产生$\binom k2$的贡献,最大化贡献 对每个$i$用单调栈预处理出$l_i$表示最小的$j$使得$j ...
- Codeforces Round #279 (Div. 2) B - Queue 水题
#include<iostream> #include<mem.h> using namespace std; ],q[]; int main() { int n,x,y; m ...