MVC生成CheckBoxList并对其验证

原文: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>
}
 

其中,用到了有关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>
}
 

 

□ 生成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
    }
}
 

 

□ 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);
        }
 
    }
}
 

 

□ 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 = "工程"}
            };
        }
    }
}            
 

参考资料:

ASP.NET MVC - CheckBoxList与ValidationMessage

时间: 2024-10-01 17:06:29

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

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

原文:[译]ASP.NET MVC 5 教程 - 10:添加验证 在本节中,我们将为Movie模型添加验证逻辑,并确认验证规则在用户试图使用程序创建和编辑电影时有效. DRY 原则 ASP.NET MVC 的一个核心原则是DRY(Don't Repeat Yourself - 不做重复的事情).ASP.NET MVC 鼓励你一次性的指定功能或行为,然后应用程序的其它地方通过映射得到它,这样一来就减少了大量的代码,从而减少了出错误的可能性,并且更易于维护. ASP.NET  MVC  和 Enti

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

原文 ASP.NET MVC 5 学习教程:添加验证 起飞网 ASP.NET MVC 5 学习教程目录: 添加控制器 添加视图 修改视图和布局页 控制器传递数据给视图 添加模型 创建连接字符串 通过控制器访问模型的数据 生成的代码详解 使用 SQL Server LocalDB Edit方法和Edit视图详解 添加查询 Entity Framework 数据迁移之添加字段 添加验证 Details 和 Delete 方法详解 在本节中,我们将为Movie模型添加验证逻辑,并确认验证规则在用户试图

如何在ASP.NET中获取随机生成的cookie加密与验证密钥

asp.net|cookie|加密|随机     本文是从ASP.NE T 1.1升级到ASP.NET 2.0需要考虑的Cookie问题的补充,通过示例代码说明如何通过反射在ASP.NET 1.1与ASP.NET 2.0中获取随机生成的cookie加密与验证密钥.ASP.NET 1.1示例代码:            object machineKeyConfig = HttpContext.Current.GetConfig("system.web/machineKey");    

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

ASP.NET MVC默认采用基于标准特性的Model验证机制,但是只有应用在Model类型及其属性上的ValidationAttribute才有效.如果我们能够将ValidationAttribute特性直接应用到参数上,我们不但可以实现简单类型(比如int.double等)数据的Model验证,还能够实现"一个Model类型,多种验证规则",本篇文章将为你提供相关的解决方案(源代码从这里下载). 一.ValidationAttribute本身是可以应用到参数上的 如果你够细心应该会

ASP.NET MVC基于标注特性的Model验证:DataAnnotationsModelValidator

对于ASP.NET MVC基于标注特性的Model验证,很多人只知道应用在数据类型及其属性上用于定义验证规则和错误消息的ValidationAttribute.通过<ASP.NET MVC以ModelValidator为核心的Model验证体系: ModelValidator>的介绍,我们知道了最终用于进行Model验证的是一个叫做ModelValidator的组件.ValidationAttribute对应的ModelValidator为DataAnnotationsModelValidat

支持ASP.NET MVC、WebFroM的表单验证框架ValidationSuar使用介绍

  这篇文章主要介绍了支持ASP.NET MVC.WebFroM的表单验证框架ValidationSuar使用介绍,本文详细讲解了使用步骤,并给出一个完整Demo下载,需要的朋友可以参考下 1.支持javascript端和后端的双重验证 (前端目前依赖于jquery.validate.js,也可以自已扩展) 2.代码简洁 3.调用方便 4.功能齐全 使用方法: 新建初始化类,将所有需要验证的在该类进行初始化,语法相当简洁并且可以统一管理,写完这个类你的验证就完成了70% 函数介绍: Add 默认

asp.net动态生成控件-asp.net 动态生成checkboxlist的问题

问题描述 asp.net 动态生成checkboxlist的问题 从数据库随机取一些记录动态生成多个checkboxlist,怎么把用户选择的结果保存?好像一点提交,checkboxlist就重新生成了,由于每个checkboxlist的item数量不一样,得到的结果总是出错. 解决方案 便利checkboxlist,用逗号拼接,存入数据库字段 解决方案二: ASP.NET动态生成HTML页面Asp.Net 中 动态生成 Excel 解决方案三: 遍历没问题,可是已提交页面要刷新,checkbo

mvc4-怎么把MVC生成的table表格导出来啊,看了很多网上的资料,都没说清楚

问题描述 怎么把MVC生成的table表格导出来啊,看了很多网上的资料,都没说清楚 怎么把MVC生成的table表格导出来啊,看了很多网上的资料,都没说清楚,求详细步骤,包括视图和控制器里面的代码 解决方案 控制器: public ActionResult View(int ID) { string strSql = "select * from Student"; DataTable dt = DbHelper.ExecuteDataTable(strSql); //获得DataTa

[ASP.NET MVC]如何定制Numeric属性/字段验证消息

对于一个Numeric属性/字段,ASP.NET MVC会自动进行数据类型的验证(客户端验证),以确保输入的是一个有效的数字,但是呈现在页面上的错误消息总是一段固定的文本:"The field {0} must be a number",本篇提供一种解决方案使我们可以对此验证消息进行定制.[源代码从这里下载] 目录 一.针对Numeric属性/字段默认验证消息 二.默认的验证消息来源于何处? 三.通过自定义ModelValidatorProvider替换NumericModelVali