加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

让我们的ASP.NET MVC应用可以单独维护验证消息

发布时间:2020-12-16 09:05:51 所属栏目:asp.Net 来源:网络整理
导读:在项目开发中,我们会使用到很多的描述性文字,比如验证消息、错误消息和确认消息等,让这些文本消息具有可维护性具有重要的意义。虽然我们可以将它们存储于资源文件中,并且ASP.NET的ValidationAttribute也对这种方式提供了原生的支持。但是资源文件的每个

在项目开发中,我们会使用到很多的描述性文字,比如验证消息、错误消息和确认消息等,让这些文本消息具有可维护性具有重要的意义。虽然我们可以将它们存储于资源文件中,并且ASP.NET的ValidationAttribute也对这种方式提供了原生的支持。但是资源文件的每个条目仅仅是简单的键-值对,只能存储消息的文本值而已,在我们的项目开发中使用的是专门的一个维护消息的组件。在这篇文章中将会通过扩展现有的ValidationAttribute特性让ASP.NET MVC应用可以使用我们的消息组件来获取验证消息。[源代码从这里下载]

一、ExtendedValidationAttribute

我们通过如下一个MessageManager来模拟我们独立的消息组件。简单起见,我们通过一个静态字典来维护所有的消息,Key和Value分别代表消息的Id和文本值。从如下的代码可以看出,消息文本可以支持{0}、{1}、…形式表示站位符。GetMessage方法根据指定的消息ID和替换站位符的对象数组格式化一个完成得消息文本。

   1: public class MessageManager
   3:     static Dictionary<string,string> messages = new Dictionary<string>();
   5:     {
   7:         messages.Add("GreaterThan",1)">"The "{0}" must be greater than "{1}"!");
   9:     }
  11:     {
  13:     }
  15: }

通过直接继承ValidationAttribute的方式,我们定义了如下一个ExtendedValidationAttribute。我们仅仅定义了一个将消息ID和替换站位符的对象数组作为参数的构造函数,而该构造函数直接调用基类包含Func<string>参数的构造函数。至于用于获取验证消息Func<string>对象,则使用调用MessageManager的GetMessage方法来构建。

   2: { 
   4:         base(()=>MessageManager.Current.GetMessage(messageId,args))
   6:     }
   1: [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.Property,AllowMultiple = false)]
   3: {
   5:     public RequiredAttribute(object[] args) :
   7:     {}
   9:     {
  11:     }
  13:? 
  15: class RangeAttribute : ExtendedValidationAttribute
  17:     private System.ComponentModel.DataAnnotations.RangeAttribute innerRangeAttribute;
  19:     public RangeAttribute(double minimum,1)">double maximum,1)" id="lnum20">  20:           21:     {
  23:     }
  25:     int minimum,1)">int maximum,1)">object[] args):  
  28:         innerRangeAttribute =   29:     }
  31:     public RangeAttribute(Type type,1)">string minimum,1)">string maximum,1)" id="lnum32">  32:           33:     {
  36:? 
  38:     {
  40:     }
class Person
string Name { get; set; }
   6:     int Age { get; set; }
double Weight { get; set; }
class HomeController : Controller
public ActionResult Index()
   5:         return View(new Person { Name = "Zhan San",Age = 24,Weight = 120 });
   8:     [HttpPost]
  10:     {
  12:         {
  14:         }
  16:     }
   1: @model Artech.Web.Mvc.Extensions.Person
   3: @{
   5: }
   7: <h2>Index</h2>
   9: {
  11: <input type="submit" value="Save" />