当前位置: 首页 > news >正文

ASP.NET MVC ModelState与数据验证【转】

为什么80%的码农都做不了架构师?>>>   hot3.png

ViewData有一个ModelState的属性,这是一个类型为ModelStateDictionary的ModelState类型的字典集合。在进行数据验证的时候这个属性是比较有用的。在使用Html.ValidationMessage()的时候,就是从ViewData.ModelState中检测是否有指定的KEY,如果存在,就提示错误信息。例如在前一篇文章ASP.NET MVC 入门7、Hellper与数据的提交与绑定中使用到的UpdateModel方法:

image

我们在View中使用Html.ValidationMessage(string modelName)来对指定的属性进行验证:

image

Html.ValidationMessage()有几个重载:

image

其中ValidationSummary()是用于显示全部的验证信息的。跟ASP.NET里面的ValidationSummary验证控件差不多。

我们测试一下/Admin/Setting页面:

image

在用UpdateModel方法更新BlogSettings.Instance.PostsPerPage的时候,当我们如图所示填写"10d"的时候,由于PostsPerPage为整型的,所以UpdateModel方法就会出错,同时会往ViewData.ModelState添加相应的错误信息,从而Html.ValidationMessage()方法就可以从ViewData.ModelState中检测到错误并提示。同时Html.ValidationMessage()方法会为出错的属性的输入框添加一个名为"input-validation-error"的CSS类,同时后面的提示信息的CSS类名为"field-validation-error":

image

CSS类的样式是可以由我们自己自由定义的。如上图的红色高亮显示。

好,下面我们来实现发表新随笔的功能。我们先写一个提供用户输入随笔内容的表单页面:

复制代码

<p>
<label for="Title">标题</label>
<%=Html.TextBox("Title", new { id = "Title", @class = "required" })%>
<%=Html.ValidationMessage("Title")%>
</p>
<p>
<label for="Content">内容</label>
<%=Html.TextArea("Content")%>
<%=Html.ValidationMessage("Content")%>
</p>
<p>
<label for="Slug">URL地址别名(如果为空则和标题同名)</label>
<%=Html.TextBox("Slug", new { id = "Slug", @class = "required" })%>
<%=Html.ValidationMessage("Slug")%>
</p>

复制代码

然后我们对用户提交过来的数据进行保存:

复制代码

[AcceptVerbs("POST"), ActionName("NewPost")]
public ActionResult SaveNewPost(FormCollection form)
{
    Post post = new Post();
try
    {
        UpdateModel(post, new[] { "Title", "Content", "Slug" });
    }
catch
    {
return View(post);
    }
    post.Save();
return ShowMsg(new List<string>() { "发表新随笔成功" });
}

复制代码

由于这三个值都是字符串类型,所以如果值为空的话,UpdateModel也是不会出错的,而我们的Title和Content是不允许为空的,或者我们想我们的Slug的长度不能超过100,也就是需要有我们自己的业务规则。这时候我们或许会这样写:

复制代码

try
{
    UpdateModel(post, new[] { "Title", "Content", "Slug" });
}
catch
{
return View(post);
}
if (string.IsNullOrEmpty(post.Title))
{
    ViewData.ModelState.AddModelError("Title", post.Title, "标题不能为空");
}
if (string.IsNullOrEmpty(post.Content))
{
    ViewData.ModelState.AddModelError("Content", post.Content, "内容不能为空");
}
if (!ViewData.ModelState.IsValid)
{
return View(post);
}

复制代码

ViewData.ModelState提供了一个AddModelError的方法,方便我们添加验证失败的信息。我们可以如上代码这样进行对象的业务规则验证,但是一旦业务规则多了,这样的代码是非常壮观的,而且不好控制。那么我们该怎么更好的进行业务规则的验证呢?得意于BlogEngine.Net的良好架构,我们可以很轻松的完成这一点。

首先,让我们修改一下BlogEngine.Core里面BusinessBase的代码。我们前面说过,BusinessBase实现了IDataErrorInfo接口,该接口有个索引器,导致ViewData.Eval()方法调用时搜索索引器的值时返回String.Empty而使ViewData.Eval()认为是找到值了,从而失效。

image

我们可以将return string.Empty修改为return null。但我们这里并不需要用到这个接口,所以我们把该接口去掉,并把相应的代码注释了。然后我们再暴露一个BrokenRules的属性,用于返回当前的所有破坏性业务规则(红框部分代码为我们添加的):

image

BusinessBase提供了一个抽象的ValidationRules方法,用于在业务类重写这个方法往里面添加验证规则(具体请看BusinessBase的Validation节)。

复制代码

ExpandedBlockStart.gif
ExpandedBlockStart.gif#region Validation
InBlock.gif
InBlock.gifprivate StringDictionary _BrokenRules = new StringDictionary();
ExpandedSubBlockStart.gif/// <summary>
InBlock.gif/// 获取所有的破坏性规则。
InBlock.gif/// 在获取前请用IsValid进行判断。
ExpandedSubBlockEnd.gif/// </summary>
InBlock.gifpublic StringDictionary BrokenRules
ExpandedSubBlockStart.gif{
InBlock.gif get
ExpandedSubBlockStart.gif {
InBlock.gif return _BrokenRules;
ExpandedSubBlockEnd.gif    }
ExpandedSubBlockEnd.gif}
InBlock.gif
ExpandedSubBlockStart.gif/// <summary>
InBlock.gif/// Add or remove a broken rule.
InBlock.gif/// </summary>
InBlock.gif/// <param name="propertyName">The name of the property.</param>
InBlock.gif/// <param name="errorMessage">The description of the error</param>
ExpandedSubBlockEnd.gif/// <param name="isBroken">True if the validation rule is broken.</param>
InBlock.gifprotected virtual void AddRule(string propertyName, string errorMessage, bool isBroken)
ExpandedSubBlockStart.gif{
InBlock.gif if (isBroken)
ExpandedSubBlockStart.gif {
InBlock.gif        _BrokenRules[propertyName] = errorMessage;
ExpandedSubBlockEnd.gif    }
InBlock.gif else
ExpandedSubBlockStart.gif {
InBlock.gif if (_BrokenRules.ContainsKey(propertyName))
ExpandedSubBlockStart.gif {
InBlock.gif            _BrokenRules.Remove(propertyName);
ExpandedSubBlockEnd.gif        }
ExpandedSubBlockEnd.gif    }
ExpandedSubBlockEnd.gif}
InBlock.gif
ExpandedSubBlockStart.gif/// <summary>
InBlock.gif/// Reinforces the business rules by adding additional rules to the
InBlock.gif/// broken rules collection.
ExpandedSubBlockEnd.gif/// </summary>
InBlock.gifprotected abstract void ValidationRules();
InBlock.gif
ExpandedSubBlockStart.gif/// <summary>
InBlock.gif/// Gets whether the object is valid or not.
ExpandedSubBlockEnd.gif/// </summary>
InBlock.gifpublic bool IsValid
ExpandedSubBlockStart.gif{
InBlock.gif get
ExpandedSubBlockStart.gif {
InBlock.gif        ValidationRules();
InBlock.gif return this._BrokenRules.Count == 0;
ExpandedSubBlockEnd.gif    }
ExpandedSubBlockEnd.gif}
InBlock.gif
ExpandedSubBlockStart.gif/// /// <summary>
InBlock.gif/// If the object has broken business rules, use this property to get access
InBlock.gif/// to the different validation messages.
ExpandedSubBlockEnd.gif/// </summary>
InBlock.gifpublic virtual string ValidationMessage
ExpandedSubBlockStart.gif{
InBlock.gif get
ExpandedSubBlockStart.gif {
InBlock.gif if (!IsValid)
ExpandedSubBlockStart.gif {
InBlock.gif            StringBuilder sb = new StringBuilder();
InBlock.gif foreach (string messages in this._BrokenRules.Values)
ExpandedSubBlockStart.gif {
InBlock.gif                sb.AppendLine(messages);
ExpandedSubBlockEnd.gif            }
InBlock.gif
InBlock.gif return sb.ToString();
ExpandedSubBlockEnd.gif        }
InBlock.gif
InBlock.gif return string.Empty;
ExpandedSubBlockEnd.gif    }
ExpandedSubBlockEnd.gif}
InBlock.gif
ExpandedBlockEnd.gif#endregion

复制代码

我们在Post类中重写这个方法来添加验证规则:

image

然后我们可以在Controller的Action中很优雅的书写我们的代码来进行业务规则的验证:

复制代码

[AcceptVerbs("POST"), ActionName("NewPost")]
public ActionResult SaveNewPost(FormCollection form)
{
    Post post = new Post();
try
    {
        UpdateModel(post, new[] { "Title", "Content", "Slug" });
    }
catch
    {
return View(post);
    }
if (!post.IsValid)
    {
foreach (string key in post.BrokenRules.Keys)
        {
            ViewData.ModelState.AddModelError(key, form[key], post.BrokenRules[key]);
        }
return View(post);
    }
    post.Save();
return ShowMsg(new List<string>() { "发表新随笔成功" });
}

复制代码

我们注意到上面的Action中用到了一个FormCollection 的参数,这个参数系统会自动将Form提交过来的全部表单值(Request.Form)赋给它的。客户端验证可以用jQuery的验证插件来,这里就不罗嗦了。

暂时就写这么多吧,想到什么再补充。Enjoy!Post by Q.Lee.lulu。

本文的Blog程序示例代码: 4mvcBlog_8.rar

物流,配货,货运,网站,论坛,交流,信息发布
网站建设QQ:471226865

转载于:https://my.oschina.net/wzzz/blog/73360

相关文章:

  • Xenserver中启动虚拟机失败Vdi is not available的另外一种处理方法
  • 网站制作 时光网11月4日又回来了
  • Oracle_Database_11g_标准版_企业版__下载地址_详细列表
  • 整理软件成熟度等级3(CMMI3)之决策分析和决定
  • 虚拟内存安排
  • 变量应用:页面传Axure变量值
  • ubuntu系统常用命令操作
  • C#操纵XML小结_转载
  • VS2008编译的程序在某些机器上运行提示“由于应用程序配置不正确,应用程序未能启动”的问题...
  • 软件测试工程师的角度看论证学问
  • HDU 4370 0 or 1
  • 变量的自动初始化
  • 编译安装apache+mysql+php 支持jpg,gd等
  • Java程序员必知的8大排序
  • 网络营销策划:揭秘企业营销策划方案三大法则
  • 【干货分享】SpringCloud微服务架构分布式组件如何共享session对象
  • ES学习笔记(12)--Symbol
  • extjs4学习之配置
  • JAVA多线程机制解析-volatilesynchronized
  • java概述
  • JS函数式编程 数组部分风格 ES6版
  • Laravel 中的一个后期静态绑定
  • mysql 5.6 原生Online DDL解析
  • SAP云平台里Global Account和Sub Account的关系
  • Spring框架之我见(三)——IOC、AOP
  • Twitter赢在开放,三年创造奇迹
  • vue--为什么data属性必须是一个函数
  • 复杂数据处理
  • 思否第一天
  • elasticsearch-head插件安装
  • TPG领衔财团投资轻奢珠宝品牌APM Monaco
  • ​插件化DPI在商用WIFI中的价值
  • #mysql 8.0 踩坑日记
  • #我与Java虚拟机的故事#连载04:一本让自己没面子的书
  • ( )的作用是将计算机中的信息传送给用户,计算机应用基础 吉大15春学期《计算机应用基础》在线作业二及答案...
  • (12)Hive调优——count distinct去重优化
  • (C语言)strcpy与strcpy详解,与模拟实现
  • (附源码)ssm考生评分系统 毕业设计 071114
  • (附源码)ssm跨平台教学系统 毕业设计 280843
  • (剑指Offer)面试题34:丑数
  • (转) RFS+AutoItLibrary测试web对话框
  • (转)Sql Server 保留几位小数的两种做法
  • ***详解账号泄露:全球约1亿用户已泄露
  • *上位机的定义
  • .net framework4与其client profile版本的区别
  • .Net MVC + EF搭建学生管理系统
  • .net 反编译_.net反编译的相关问题
  • .net快速开发框架源码分享
  • /etc/X11/xorg.conf 文件被误改后进不了图形化界面
  • ?php echo $logosrc[0];?,如何在一行中显示logo和标题?
  • @data注解_一枚 架构师 也不会用的Lombok注解,相见恨晚
  • [ vulhub漏洞复现篇 ] AppWeb认证绕过漏洞(CVE-2018-8715)
  • [16/N]论得趣
  • [2]十道算法题【Java实现】
  • [20170728]oracle保留字.txt