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视图层和控制层的.如果是大规模的应用程序,经常会由不同功能的模块组成,而每个功能模块 ...
 
随机推荐
- 树莓派3B安装远程
			
步骤1:树莓派3安装 RDP SERVER 及VNC SERVER sudo apt-get install -y tightvncserver sudo vncserver 最后才知道一定要加上VN ...
 - HTML--1
			
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...
 - ViewPager中的子Activity无法响应OnActivityResult的解决方法
			
ViewPager子Activity通过startActivityForResult()跳转至OtherActivity,OtherActivity回传结果由ViewPager所在的父Activity ...
 - bzoj 2752
			
2752 思路: 线段树: 代码: #include <cstdio> #include <cstring> #include <iostream> #includ ...
 - STL容器读书笔记
			
vector vector维护的是一个连续线性空间 vector是动态空间,随着元素的加入会自动扩容,扩充至当前size的两倍,然后将原内容拷贝,开始在原内容之后构造新元素,并释放空间 vector提 ...
 - loadrunner录制时,设置能不记录所有的事件
			
loadrunner录制时,设置能不记录所有的事件 可以做如下两点设置: 1. 在record option下的recording选项卡下选择html advance,在script type下选择A ...
 - Ionic实战六:日期选择控件
			
onic日期选择控件,用于ionic项目开发中的日期选择以及日期插件   
 - 用profile协助程序性能优化
			
程序运行慢的原因有很多,比如存在太多的劣化代码(如在程序中存在大量的“.”操作符),但真正的原因往往是比较是一两段设计并不那么良好的不起眼的程序,比如对一序列元素进行自定义的类型转换等.因为程序性能 ...
 - Loj #6560 小奇取石子
			
题面 分类讨论一波,n小的暴力2^n,n大的背包. #include<bits/stdc++.h> #define ll long long using namespace std; co ...
 - 20162307  课堂测试 hash
			
20162307 课堂测试 hash 作业要求 利用除留余数法为下列关键字集合的存储设计hash函数,并画出分别用开放寻址法和拉链法解决冲突得到的空间存储状态(散列因子取0.75) 关键字集合:85, ...