原文:MVC生成CheckBoxList并对其验证

通过扩展方法,可以让CheckBox水平排列,生成CheckBoxList,正如"MVC扩展生成CheckBoxList并水平排列"一文。但,如何对生成的CheckBoxList验证呢?比如要求至少勾选一项:

 

□ 思路

在强类型视图页中,@Html.EditorFor(model => model.属性, "模版名称", new{ ...路由数据...}),模版名称对应Views/Shared/EditorTemplates/CheckBoxList.cshtml部分视图,路由数据用来传递生成CheckBoxList所需要的一切,并在CheckBoxList.cshtml中显示错误信息,最后CheckBoxList的生成交给扩展方法。

□ Model

    public class Course
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

using System.ComponentModel.DataAnnotations;

namespace MvcApplication1.Models
{
    public class Student
    {
        [Display(Name = "姓名")]
        [Required(ErrorMessage = "必填")]
        [StringLength(100, ErrorMessage = "最大长度100")]
        public string Name { get; set; }

        [Display(Name = "所选课程")]
        [Required(ErrorMessage = "至少选择一个课程")]
        public string Courses{ get; set; }
    }
}

 

□ 在_Layout.cshtml中启用客户端异步验证

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("/bundles/jqueryval") //启用客户端异步验证
    @RenderSection("scripts", required: false)

 

□ Home/Index.cshtml

@using MvcApplication1.Infrastructure.Enums
@model MvcApplication1.Models.Student
 
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
 
@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)
 
    <fieldset>
        <legend>Student</legend>
        <div class="editor-label">
            @Html.LabelFor(model => model.Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Name)
            @Html.ValidationMessageFor(model => model.Name)
        </div>
        
        <div class="editor-label">
            @Html.LabelFor(model => model.Courses)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Courses, "CheckBoxList", new
            {
                TagName = "Courses",
                CheckBoxItems = ViewBag.Course,
                Position = Position.Horizontal,
                Numbers = 3
            })
        </div>
        
        <p>
            <input type="submit" value="创建"/>
        </p>
    </fieldset>
}
 

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

其中,用到了有关CheckBoxList水平或垂直排列的一个枚举:

namespace MvcApplication1.Infrastructure.Enums

{

    public enum Position

    {

        Horizontal,

        Vertical

    }

}  

生成CheckBoxList的路由数据,以及模版名称:

            @Html.EditorFor(model => model.Courses, "CheckBoxList", new

            {

                TagName = "Courses",

                CheckBoxItems = ViewBag.Course,

                Position = Position.Horizontal,

                Numbers = 3

            })

 

□ Views/Shared/EditorTemplates/CheckBoxList.cshtml

@using MvcApplication1.Infrastructure.Enums
@{
    var required = false;
    object validationMessage = string.Empty;
 
    //获取客户端验证属性
    var validationAttributes = Html.GetUnobtrusiveValidationAttributes(""); 
    if (validationAttributes.ContainsKey("data-val") && validationAttributes.ContainsKey("data-val-required"))
    {
        required = true;
        if (!validationAttributes.TryGetValue("data-val-required", out validationMessage))
        {
            validationMessage = "This field is required.";
        }
        validationAttributes.Add("required","required");
    }
 
    var tagName = ViewData["TagName"] == null ? "CheckBoxList" : (string)ViewData["TagName"];
    var checkboxItems = ViewData["CheckBoxItems"] == null ? new List<SelectListItem>() : (IEnumerable<SelectListItem>)ViewData["CheckBoxItems"];
    var position = ViewData["Position"] == null ? Position.Horizontal : (Position)ViewData["Position"];
 
    var numbers = 0;
    if (ViewData["Numbers"] == null)
    {
        numbers = 1;
    }
    else if (!int.TryParse(ViewData["Numbers"].ToString(), out numbers))
    {
        numbers = 1;
    }
    else
    {
        numbers = (int)ViewData["Numbers"];
    }
}
 
@Html.CheckBoxList(
tagName,
checkboxItems,
new RouteValueDictionary(validationAttributes),
position,
numbers)
 
@if (required)
{
    <span class="field-validation-valid" data-valmsg-for="@(tagName)" data-valmsg-replace="false">
        @validationMessage
    </span>
}
 

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

□ 生成CheckBoxList的扩展方法

using System.Collections.Generic;
using System.Linq;
using System.Text;
using MvcApplication1.Infrastructure.Enums;
 
namespace System.Web.Mvc
{
    public static class CheckBoxListExtensions
    {
        #region 水平方向
        /// <summary>
        /// CheckBoxList
        /// </summary>
        /// <param name="htmlHelper">HTML helper</param>
        /// <param name="name"></param>
        /// <param name="listInfo"></param>
        /// <param name="htmlAttributes"></param>
        /// <param name="number">每行显式的个数</param>
        /// <returns></returns>
        public static MvcHtmlString CheckBoxList(this HtmlHelper htmlHelper,
            string name,
            IEnumerable<SelectListItem> listInfo,
            IDictionary<string, object> htmlAttributes,
            int number)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentException("必须给CheckBoxList一个name值", "name");
            }
            if (listInfo == null)
            {
                throw new ArgumentNullException("listInfo", "List<SelectListItem> listInfo不能为null");
            }
 
            var selectListItems = listInfo as SelectListItem[] ?? listInfo.ToArray();
            if (!selectListItems.Any())
            {
                throw new ArgumentException("List<SelectListItem> listInfo 至少有一组资料", "listInfo");
            }
 
            var sb = new StringBuilder();
            var lineNumber = 0;
            foreach (var info in selectListItems)
            {
                lineNumber++;
                var builder = new TagBuilder("input");
                if (info.Selected)
                {
                    builder.MergeAttribute("checked", "checked");
                }
                builder.MergeAttributes(htmlAttributes);
                builder.MergeAttribute("type", "checkbox");
                builder.MergeAttribute("value", info.Value);
                builder.MergeAttribute("name", name);
                builder.MergeAttribute("id", string.Format("{0}_{1}", name, info.Value));
                sb.Append(builder.ToString(TagRenderMode.Normal));
 
                var labelBuilder = new TagBuilder("label");
                labelBuilder.MergeAttribute("for", string.Format("{0}_{1}", name, info.Value));
                labelBuilder.InnerHtml = info.Text;
                sb.Append(labelBuilder.ToString(TagRenderMode.Normal));
 
                if (number == 0 || (lineNumber % number == 0))
                {
                    sb.Append("<br />");
                }
            }
            return MvcHtmlString.Create(sb.ToString());
        }
 
        public static MvcHtmlString CheckBoxList(this HtmlHelper htmlHelper,
            string name,
            IEnumerable<SelectListItem> listInfo)
        {
            return htmlHelper.CheckBoxList(name, listInfo, (IDictionary<string, object>) null, 0);
        }
        #endregion
 
        #region 垂直方向
 
        public static MvcHtmlString CheckBoxListVertical(this HtmlHelper htmlHelper,
            string name,
            IEnumerable<SelectListItem> listInfo,
            IDictionary<string, object> htmlAttributes,
            int columnNumber = 1)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentException("必须给CheckBoxList的name属性赋值", "name");
            }
            if (listInfo == null)
            {
                throw new ArgumentNullException("listInfo", "List<SelectListInfo> listInfo不能为null");
            }
 
            var selectListItmes = listInfo as SelectListItem[] ?? listInfo.ToArray();
            if (!selectListItmes.Any())
            {
                throw new ArgumentException("List<SelectListItem> listInfo不能为null","listInfo");
            }
 
            var dataCount = selectListItmes.Count();
            var rows = Convert.ToInt32(Math.Ceiling(Convert.ToDecimal(dataCount)/Convert.ToDecimal(columnNumber)));
            if (dataCount <= columnNumber || dataCount - columnNumber == 1)
            {
                rows = dataCount;
            }
 
            var wrapBuilder = new TagBuilder("div");
            wrapBuilder.MergeAttribute("style","float:left; line-height:25px; padding-right:5px;");
            var wrapStart = wrapBuilder.ToString(TagRenderMode.StartTag);
            var wrapClose = string.Concat(wrapBuilder.ToString(TagRenderMode.EndTag),
                " <div style=\"clear:both;\"></div>");
            var wrapBreak = string.Concat("</div>", wrapBuilder.ToString(TagRenderMode.StartTag));
 
            var sb = new StringBuilder();
            sb.Append(wrapStart);
 
            var lineNumber = 0;
            foreach (var info in selectListItmes)
            {
                var builder = new TagBuilder("input");
                if (info.Selected)
                {
                    builder.MergeAttribute("checked","checked");
                }
                builder.MergeAttributes(htmlAttributes);
                builder.MergeAttribute("type","checkbox");
                builder.MergeAttribute("value", info.Value);
                builder.MergeAttribute("name", name);
                builder.MergeAttribute("id", string.Format("{0}_{1}",name, info.Value));
                sb.Append(builder.ToString(TagRenderMode.Normal));
 
                var labelBuilder = new TagBuilder("label");
                labelBuilder.MergeAttribute("for", string.Format("{0}_{1}", name, info.Value));
                labelBuilder.InnerHtml = info.Text;
                sb.Append(labelBuilder.ToString(TagRenderMode.Normal));
 
                lineNumber++;
 
                if (lineNumber.Equals(rows))
                {
                    sb.Append(wrapBreak);
                    lineNumber = 0;
                }
                else
                {
                    sb.Append("<br />");
                }
            }
            sb.Append(wrapClose);
            return MvcHtmlString.Create(sb.ToString());
        }
        #endregion
 
        #region 水平或垂直方向
 
        public static MvcHtmlString CheckBoxList(this HtmlHelper htmlHelper,
            string name,
            IEnumerable<SelectListItem> listInfo,
            IDictionary<string, object> htmlAttributes,
            Position position = Position.Horizontal,
            int number = 0)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentException("必须给CheckBoxList的name属性赋值","name");
            }
            if (listInfo == null)
            {
                throw new ArgumentNullException("listInfo", "List<SelectListItem> listInfo不能为null");
            }
            var selectListItems = listInfo as SelectListItem[] ?? listInfo.ToArray();
            if (!selectListItems.Any())
            {
                throw new ArgumentException("List<SelectListItem> listInfo至少要一组资料","listInfo");
            }
 
            var sb = new StringBuilder();
            var lineNumber = 0;
            switch (position)
            {
                case Position.Horizontal:
                    foreach (var info in selectListItems)
                    {
                        lineNumber++;
                        sb.Append(CreateCheckBoxItem(info, name, htmlAttributes));
 
                        if (number == 0 || (lineNumber%number == 0))
                        {
                            sb.Append("<br />");
                        }
                    }
                    sb.Append("<br />");
                    break;
                case Position.Vertical:
                    var dataCount = selectListItems.Count();
                    var rows = Convert.ToInt32(Math.Ceiling(Convert.ToDecimal(dataCount)/Convert.ToDecimal(number)));
                    if (dataCount <= number || dataCount - number == 1)
                    {
                        rows = dataCount;
                    }
 
                    var wrapBuilder = new TagBuilder("div");
                    wrapBuilder.MergeAttribute("style","float:left; line-height:25px; padding-right:5px;");
                    var wrapStart = wrapBuilder.ToString(TagRenderMode.StartTag);
                    var wrapClose = string.Concat(wrapBuilder.ToString(TagRenderMode.EndTag), " <div style=\"clear:both;\"></div>");
                    var wrapBreak = string.Concat("</div>", wrapBuilder.ToString(TagRenderMode.StartTag));
                    sb.Append(wrapStart);
 
                    foreach (var info in selectListItems)
                    {
                        lineNumber++;
                        sb.Append(CreateCheckBoxItem(info, name, htmlAttributes));
 
                        if (lineNumber.Equals(rows))
                        {
                            sb.Append(wrapBreak);
                            lineNumber = 0;
                        }
                        else
                        {
                            sb.Append(wrapClose);
                        }
                    }
                    sb.Append(wrapClose);
                    break;
            }
            return MvcHtmlString.Create(sb.ToString());
        }
 
        internal static string CreateCheckBoxItem(SelectListItem info, string name,
            IDictionary<string, object> htmlAttributes)
        {
            var sb = new StringBuilder();
            var builder = new TagBuilder("input");
            if (info.Selected)
            {
                builder.MergeAttribute("checked","checked");
            }
            builder.MergeAttributes(htmlAttributes);
            builder.MergeAttribute("type", "checkbox");
            builder.MergeAttribute("value", info.Value);
            builder.MergeAttribute("name", name);
            builder.MergeAttribute("id", string.Format("{0}_{1}", name, info.Value));
            sb.Append(builder.ToString(TagRenderMode.Normal));
 
            var labelBuilder = new TagBuilder("label");
            labelBuilder.MergeAttribute("for", string.Format("{0}_{1}", name, info.Value));
            labelBuilder.InnerHtml = info.Text;
            sb.Append(labelBuilder.ToString(TagRenderMode.Normal));
 
            return sb.ToString();
        }
        #endregion
    }
}
 

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

□ HomeController

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication1.Infrastructure.Services;
using MvcApplication1.Models;
 
namespace MvcApplication1.Controllers
{
    public class HomeController : Controller
    {
        private readonly  CourseService service = new CourseService();
 
        private List<SelectListItem> coursesSelectListItems
        {
            get
            {
                var courses = this.service.GetCourses();
                var items = new List<SelectListItem>();
                foreach (var c in courses)
                {
                    items.Add(new SelectListItem()
                    {
                        Value = c.Id.ToString(),
                        Text = c.Name
                    });
                }
                return items;
            }
 
        }
 
        public ActionResult Index()
        {
            ViewBag.Course = this.coursesSelectListItems;
            return View();
        }
 
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Index(Student stu)
        {
            ViewBag.Course = this.coursesSelectListItems;
            if (ModelState.IsValid)
            {
                return View();
            }
            return View(stu);
        }
 
    }
}
 

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

□ CouseService.cs

using System.Collections.Generic;
using MvcApplication1.Models;
 
namespace MvcApplication1.Infrastructure.Services
{
    public class CourseService
    {
        public IEnumerable<Course> GetCourses()
        {
            return new List<Course>()
            {
                new Course(){Id = 1, Name = "语文"},
                new Course(){Id = 2, Name = "数学"},
                new Course(){Id = 3, Name = "哲学"},
                new Course(){Id = 4, Name = "英语"},
                new Course(){Id = 5,Name = "法语"},
                new Course(){Id = 6, Name = "物理"},
                new Course(){Id = 7, Name = "化学"},
                new Course(){Id = 8, Name = "工程"}
            };
        }
    }
}            
 

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

参考资料:

ASP.NET MVC - CheckBoxList与ValidationMessage

MVC生成CheckBoxList并对其验证的更多相关文章

  1. 再议ASP.NET MVC中CheckBoxList的验证

    在ASP.NET MVC 4中谈到CheckBoxList,经常是与CheckBoxList的显示以及验证有关.我在"MVC扩展生成CheckBoxList并水平排列"中通过扩展H ...

  2. MVC中CheckBoxList的3种实现方式

    比如,当为一个用户设置角色的时候,角色通常以CheckBoxList的形式呈现.用户和角色是多对多关系: using System.Collections.Generic; using System. ...

  3. MVC扩展生成CheckBoxList并水平排列

    本篇体验生成CheckBoxList的几个思路,扩展MVC的HtmlHelper生成CheckBoxList,并使之水平排开.     通过遍历从控制器方法拿到的Model集合 □ 思路 比如为一个用 ...

  4. [ASP.NET MVC 小牛之路]16 - Model 验证

    上一篇博文 [ASP.NET MVC 小牛之路]15 - Model Binding 中讲了MVC在Model Binding过程中如何根据用户提交HTTP请求数据创建Model对象.在实际的项目中, ...

  5. MVC中的数据注解和验证

    数据注解和验证 用户输入验证在客户端浏览器中需要执行验证逻辑. 在客户端也需要执行. 注解是一种通用机制, 可以用来向框架注入元数据, 同时, 框架不只驱动元数据的验证, 还可以在生成显示和编辑模型的 ...

  6. ASP.NET MVC 5 学习教程:添加验证

    原文 ASP.NET MVC 5 学习教程:添加验证 起飞网 ASP.NET MVC 5 学习教程目录: 添加控制器 添加视图 修改视图和布局页 控制器传递数据给视图 添加模型 创建连接字符串 通过控 ...

  7. 【译】ASP.NET MVC 5 教程 - 10:添加验证

    原文:[译]ASP.NET MVC 5 教程 - 10:添加验证 在本节中,我们将为Movie模型添加验证逻辑,并确认验证规则在用户试图使用程序创建和编辑电影时有效. DRY 原则 ASP.NET M ...

  8. ASP.NET MVC基于标注特性的Model验证:将ValidationAttribute应用到参数上

    原文:ASP.NET MVC基于标注特性的Model验证:将ValidationAttribute应用到参数上 ASP.NET MVC默认采用基于标准特性的Model验证机制,但是只有应用在Model ...

  9. ASP.NET没有魔法——ASP.NET MVC使用Oauth2.0实现身份验证

    随着软件的不断发展,出现了更多的身份验证使用场景,除了典型的服务器与客户端之间的身份验证外还有,如服务与服务之间的(如微服务架构).服务器与多种客户端的(如PC.移动.Web等),甚至还有需要以服务的 ...

随机推荐

  1. 使用 svn+maven+jenkins(hudson)+Publish Over SSH plugins 构建持续集成及自动远程发布体系(转)

    1.安装jenkins 2.浏览器访问jenkins主页 http://192.168.0.1:8080/,点击“系统管理” 3.在插件管理中,安装Publish Over SSH插件 4.在系统设置 ...

  2. [DEEP LEARNING An MIT Press book in preparation]Deep Learning for AI

    动人的DL我们有六个月的时间,积累了一定的经验,实验,也DL有了一些自己的想法和理解.曾经想扩大和加深DL相关方面的一些知识. 然后看到了一个MIT按有关的对出版物DL图书http://www.iro ...

  3. Socket方法LAN多线程文件传输

    1.思维:为了实现各种文件的大小可以被发送和接收的,它可以被设置为发送和接收缓冲器环.并记录文件的位置读取,假设读入缓冲区的字节的特定数目大于缓冲区的大小较小.然后该文件被发送,退出发送周期,关闭连接 ...

  4. JS它DOM

    DOM:document object model.文档对象模型.它主要由许多节点.而基于JS对象的一切视角,DOM核心是节点对象和操作方法的属性.从下面三方面来介绍DOM. 一.节点查找与操作 这部 ...

  5. 基于docker构建jenkins和svn服务(转)

    码农们很定都知道svn的重要性,机器坏掉丢代码的惨痛教训想必很多人都有. jenkins可能很多人都不了解.这是一个持续集成的工具,在敏捷开发领域很流行:跟svn结合可以实现定期build.check ...

  6. POJ 2329 (暴力+搜索bfs)

    Nearest number - 2 Time Limit: 5000MS Memory Limit: 65536K Total Submissions: 3943 Accepted: 1210 De ...

  7. C++ Primer 学习笔记_43_STL实践与分析(17)--再谈迭代器【中】

    STL实践与分析 --再谈迭代器[中] 二.iostream迭代[续] 3.ostream_iterator对象和ostream_iterator对象的使用 能够使用ostream_iterator对 ...

  8. swift UI特殊培训38 与滚动码ScrollView

    有时我们适合页面的全部内容,我们需要使用ScrollView,额外的内容打通滚动. 什么样的宽度和高度首先,定义,健身器材轻松. let pageWidth = 320 let pageHeight ...

  9. LeetCode——Linked List Cycle II

    Given a linked list, return the node where the cycle begins. If there is no cycle, return null. Foll ...

  10. CodeIgniter入门——HelloWorld

    原文:CodeIgniter入门--HelloWorld CodeIgniter(CI)是一套给PHP网站开发者使用的应用程序开发框架和工具包. 初次接触,来一个HelloWorld~~~ ^_^ 准 ...