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视图层和控制层的.如果是大规模的应用程序,经常会由不同功能的模块组成,而每个功能模块 ...
随机推荐
- Robot Framework测试框架用例脚本设计方法
Robot Framework介绍 Robot Framework是一个通用的关键字驱动自动化测试框架.测试用例以HTML,纯文本或TSV(制表符分隔的一系列值)文件存储.通过测试库中实现的关键字驱动 ...
- AdvStringGrid 复选框、goRowSelect
var I: Integer; begin do begin AdvStringGrid1.AddCheckBox(, I, True, True); AdvStringGrid1.Cells[,I] ...
- sql server中扩展存储过程
--列出服务器上安装的所有OLEDB提供的程序 execute master..xp_enum_oledb_providers --得到硬盘文件信息 --参数说明:目录名,目录深度,是否显示文件 (少 ...
- 根据条件批量删除document
curl -H "Content-Type:application/json" -XPOST http://localhost:9200/devopsrealinfo/_dele ...
- jar包重启脚本-restart.sh
#!/bin/sh PROJECT_PATH=/var/www/ PROJECT_NAME=demo.jar PROJECT_ALL_LOG_NAME=logs/demo-all.log # stop ...
- CCF CSP 201412-3 集合竞价
CCF计算机职业资格认证考试题解系列文章为meelo原创,请务必以链接形式注明本文地址 CCF CSP 201412-3 集合竞价 问题描述 某股票交易所请你编写一个程序,根据开盘前客户提交的订单来确 ...
- elastucasearch基础理论以及安装
一.elasticasearch核心概念 Near Realtime(NRT 近实时) Elasticsearch 是一个近实时的搜索平台.您索引一个文档开始直到它被查询时会有轻微的延迟时间(通常为1 ...
- Java反射机制的缺点
来自官方指南(Tutorial):http://docs.oracle.com/javase/tutorial/reflect/index.html 反射的用途 Uses of ReflectionR ...
- 常用的PHP排序算法以及应用场景
更多php排序算法应用常景:http://www.bf361.com/algorithm/algorithm-php 1.冒泡排序 冒泡排序:冒泡排序(Bubble Sort),是一种计算机科学领域 ...
- Java8Lambda表达式
“Lambda 表达式”(lambda expression)是一个匿名函数,Lambda表达式基于数学中的λ演算得名,直接对应于其中的lambda抽象(lambda abstraction),是一个 ...