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并水平排列

MVC生成CheckBoxList并对其验证

MVC中CheckBoxList的3种实现方式

时间: 2024-08-29 21:58:30

MVC中CheckBoxList的3种实现方式的相关文章

ASP.NET MVC 表单的几种提交方式

下面是总结一下在ASP.NET MVC中表单的几种提交方式. 1.Ajax提交表单 需要引用 <script type="text/javascript" src="/Scripts/jquery-1.7.2.min.js"></script>    <script src="/Scripts/jquery.validate.min.js" type="text/javascript">&l

jQuery中的Ajax几种请求方式

1. load( url, [data], [callback] ) :载入远程 HTML 文件代码并插入至 DOM 中. url (String) : 请求的HTML页的URL地址. data (Map) : (可选参数) 发送至服务器的 key/value 数据. callback (Callback) : (可选参数) 请求完成时(不需要是success的)的回调函数. 这个方法默认使用 GET 方式来传递的,如果[data]参数有传递数据进去,就会自动转换为POST方式的.jQuery

【学习笔记】——原生js中常用的四种循环方式

一.引言 本文主要是利用一个例子,讲一下原生js中常用的四种循环方式的使用与区别: 实现效果: 在网页中弹出框输入0   网页输出"欢迎下次光临" 在网页中弹出框输入1   网页输出"查询中--" 在网页中弹出框输入2   网页输出"取款中--" 在网页中弹出框输入3   网页输出"转账进行中--" 在网页中弹出框输入其他字符   网页输出"无效按键" 四种循环: for循环 while循环 for  in

Springboot中IDE支持两种打包方式,即jar包和war包

Springboot中IDE支持两种打包方式,即jar包和war包 打包之前修改pom.xml中的packaging节点,改为jar或者war    在项目的根目录执行maven 命令clean package -Dmaven.test.skip=true,即可打包,如下 命令执行成功后,在target目录下即可看到打包好的文件 提示:若打的包为jar包,可通过java -jar guns-xxx.jar来启动Guns系统 原文地址:https://www.cnblogs.com/mracale

wpf中UserControl的几种绑定方式

原文:wpf中UserControl的几种绑定方式 我们经常会抽取一些可重用的控件,某个属性是否需要重用,直接决定了这个属性的绑定方式. 1.完全不可重用的控件 有一些与业务强相关的控件,它们的属性完全来自ViewModel,越是相对复杂的控件,越容易这样.比如: // ChooseUc.xaml <UserControl> <StackPanel Orientation="Horizontal"> <Label Content="选择一个水果:

MVC中处理表单提交的方式(Ajax+Jquery)

MVC中处理表单有很多种方法,这里说到第一种方式:Ajax+Jquery 先看下表单: <form class="row form-body form-horizontal m-t"> <div class="col-md-6"> <div class="form-group"> <label class="col-sm-3 control-label">订单编号:</la

细说java中Map的两种迭代方式

以前对java中迭代方式总是迷迷糊糊的,今天总算弄懂了,特意的总结了一下,基本是算是理解透彻了. 1.再说Map之前先说下Iterator: Iterator主要用于遍历(即迭代访问)Collection集合中的元素,Iterator也称为迭代器.它仅仅只有三个方法:hasNext(),next()和remove() hasNext():如果仍有元素可以迭代,则返回 true.(换句话说,如果 next 返回了元素而不是 抛出异常,则返回 true). next():返回迭代的下一个元素. re

Android中Activity的四种启动方式

谈到Activity的启动方式必须要说的是数据结构中的栈.栈是一种只能从一端进入存储数据的线性表,它以先进后出的原则存储数据,先进入的数据压入栈底,后进入的数据在栈顶.需要读取数据的时候就需要从顶部开始读取数据,栈具有记忆功能,对栈的操作不需要指针的约束.在Android中Activity的显示其实就是一个入栈和出栈的过程.当打开一个Activity的时候Activity入栈,当关闭一个Activity的时候Activity出栈,用户操作的Activity位于栈顶,一般情况下,一个应用程序对应一

再议ASP.NET MVC中CheckBoxList的验证

在ASP.NET MVC 4中谈到CheckBoxList,经常是与CheckBoxList的显示以及验证有关.我在"MVC扩展生成CheckBoxList并水平排列"中通过扩展HtmlHelper做到了水平或垂直显示CheckBoxList.在"MVC生成CheckBoxList并对其验证"中,借助模版实现对一组CheckBoxList的验证,但如果要对多组CheckBoxList验证,这种方法也不是很好. 比如,在电商商品模块中,关于某个类别下会有多个属性,有些