原文发布时间为:2011-07-20 —— 来源于本人的百度文章 [由搬家工具导入]

Model Metadata and Validation Localization using Conventions

http://haacked.com/archive/2011/07/14/model-metadata-and-validation-localization-using-conventions.aspx

By default, ASP.NET MVC leverages Data Annotations to provide validation. The approach is easy to get started with and allows the validation applied on the server to “float” to the client without any extra work.

However, once you get localization involved, using Data Annotations can really clutter your models. For example, the following is a simple model class with two properties.

publicclass Character { publicstring FirstName { get; set; } publicstring LastName { get; set; }}

Nothing to write home about, but it is nice, clean, and simple.  To make it more useful, I’ll add validation and format how the properties are displayed.

publicclass Character { [Display(Name="First Name")] [Required] [StringLength(50)]] publicstring FirstName { get; set; } [Display(Name="Last Name")] [Required] [StringLength(50)]] publicstring LastName { get; set; }}

That’s busier, but not horrible. It sure is awful Anglo-centric though. I’ll fix that by making sure the property labels and error messages are pulled from a resource file.

publicclass Character { [Display(Name="Character_FirstName", ResourceType=typeof(ClassLib1.Resources))] [Required(ErrorMessageResourceType=typeof(ClassLib1.Resources), ErrorMessageResourceName="Character_FirstName_Required")] [StringLength(50, ErrorMessageResourceType = typeof(ClassLib1.Resources), ErrorMessageResourceName = "Character_FirstName_StringLength")] publicstring FirstName { get; set; } [Display(Name="Character_LastName", ResourceType=typeof(ClassLib1.Resources))] [Required(ErrorMessageResourceType=typeof(ClassLib1.Resources), ErrorMessageResourceName="Character_LastName_Required")] [StringLength(50, ErrorMessageResourceType = typeof(ClassLib1.Resources), ErrorMessageResourceName = "Character_LastName_StringLength")] publicstring LastName { get; set; }}

Wow! I don’t know about you, but I feel a little bit dirty typing all that in. Allow me a moment as I go wash up.

So what can I do to get rid of all that noise? Conventions to the rescue! By employing a simple set of conventions, I should be able to look up error messages in resource files as well as property labels without having to specify all that information. In fact, by convention I shouldn’t even need to use the DisplayAttribute.

I wrote a custom PROOF OF CONCEPT ModelMetadataProvider that supports this approach. More specifically, mine is derived from the DataAnnotationsModelMetadataProvider.

What Conventions Does It Apply?

The nice thing about this convention based model metadata provider is it allows you to specify as little or as much of the metadata you need and it fills in the rest.

Providing minimal metadata

For example, the following is a class with one simple property.

publicclass Character { [Required] [StringLength(50)] publicstring FirstName {get; set;}}

When displayed as a label, the custom metadata provider looks up the resource key, {ClassName}_{PropertyName}, and uses the resource value as the label. For example, for the FirstName property, the provider uses the key Character_FirstName to look up the label in the resource file. I’ll cover how resource type is specified later.

If a value for that resource is not found, the code falls back to using the property name as the label, but splits it using Pascal/Camel casing as a guide. Therefore in this case, the label is “First Name”.

The error message for a validation attribute uses a resource key of {ClassName}_{PropertyName}_{AttributeName}. For example, to locate the error message for a RequiredAttribute, the provider finds the resource key Character_FirstName_Required.

Partial Metadata

There may be cases where you can provide some metadata, but not all of it. Ideally, the metadata that you don’t supply is inferred based on the conventions. Going back to previous example again:

publicclass Character { [Required(ErrorMessageResourceType=typeof(MyResources))] [StringLength(50, ErrorMessageResourceName="StringLength_Error")] [Display(Name="First Name")] publicstring FirstName {get; set;}}

Notice that the first attribute only specifies the error message resource type. In this case, the specified resource type will override the default resource type. But the resource key is still inferred by convention (aka Character_FirstName_Required).

In contrast, notice that the second StringLengthAttribute, only specifies the resource name, and doesn’t specify a resource type. In this case, the specified resource name is used to look up the error message using the default resource type. As you might expect, if the ErrorMessage property is specified, that takes precedence over the conventions.

The DisplayAttribute works slightly differently. By default, the Name property is used as a resource key if a resource type is also specified. If no resource type is specified, the Name property is used directly. In the case of this convention based provider, an attempt to lookup a resource value using the Name property as a resource always occurs before falling back to the default behavior.

Configuration

One detail I haven’t covered yet is what resource type is used to find these messages? Is that determined by convention?

Deteriming this by convention would be tricky so it’s the one bit of information that must be explicitly specified when configuring the provider itself. The following code in Global.asax.cs shows how to configure this.

ModelMetadataProviders.Current = new ConventionalModelMetadataProvider( requireConventionAttribute: false, defaultResourceType: typeof(MyResources.Resource));

The model metadata provider’s constructor has two arguments used to configure it.

Some developers will want the conventions to apply to every model, while others will want to be explicit and have models opt in to this behavior. The first argument, requireConventionAttribute, determines whether the conventions only apply to classes with the MetadataConventionsAttribute applied.

The explicit folks will want to set this value to true so that only classes with the MetadataConventionsAttribute applied to them (or classes in an assembly where the attribute is applied to the assembly) will use these conventions.

The attribute can also be used to specify the resource type for resource strings.

The second property specifies the default resource type to use for resource strings. Note that this can be overridden by any attribute that specifies its own resource type.

Caveats, Issues, Potholes

This code is something I hacked together and there are a few issues to consider that I could not easily work around. First of all, the implementation has to mutate properties of attributes. In general, this is not a good thing to do because attributes tend to be global. If other code relies on the attributes having their original values, this could cause issues.

I think for most ASP.NET MVC applications (in fact most web applications period) this will not be an issue.

Another issue is that the conventions don’t work for implied validation. For example, if you have a property of a simple value type (such as int), the DataAnnotationsValidatorProvider supplies a RequiredValidator to validate the value. Since this validator didn’t come from an attribute, it won’t use my convention based lookup for its error messages.

I thought about making this work, but it the hooks I need to do this without a large amount of code don’t appear to be there. I’d have to write my own validator provider (as far as I can tell) or register my own validator adapters in place of the default ones. I wasn’t up to the task just yet.

Try it outLive Demo: To see a demo of it in action, check out the live demo site. NuGet Package: To try it in your application, install it using NuGet: Install-Package ModelMetadataExtensionsSource Code: The source code is up on BitBucket.

更改MVC3默认错误提示信息 模型验证 validation的更多相关文章

  1. MVC3升级到MVC4模型验证信息显示为英文问题及解决方案

    最近把项目从mvc3升级到mvc4,部署到服务器上出现了一个小问题,就是在表单里字段验证时,验证显示信息为英文,如下: The field 平均租金 must be a number 而在本地是好的, ...

  2. 模型验证与模型集成(Ensemble)

    作者:吴晓军 原文:https://zhuanlan.zhihu.com/p/27424282 模型验证(Validation) 在Test Data的标签未知的情况下,我们需要自己构造测试数据来验证 ...

  3. Python数据科学手册-机器学习之模型验证

    模型验证 model validation 就是在选择 模型 和 超参数 之后.通过对训练数据进行学习.对比模型对 已知 数据的预测值和实际值 的差异. 错误的模型验证方法. 用同一套数据训练 和 评 ...

  4. Asp.Net Web API 2第十五课——Model Validation(模型验证)

    前言 阅读本文之前,您也可以到Asp.Net Web API 2 系列导航进行查看 http://www.cnblogs.com/aehyok/p/3446289.html 本文参考链接文章地址htt ...

  5. Model Validation(模型验证)

    Model Validation(模型验证) 前言 阅读本文之前,您也可以到Asp.Net Web API 2 系列导航进行查看 http://www.cnblogs.com/aehyok/p/344 ...

  6. webapi Model Validation 模型验证

    通常情况下,对于那些经常为别人提供数据接口的开发人员来说,对于调用方传递过来的参数都会有验证处理.例如: if (string.IsNullOrEmpty(entity.Name)) { //当姓名为 ...

  7. Web API中的模型验证Model Validation

    数据注释 在ASP.NET Web API中,您可以使用System.ComponentModel.DataAnnotations命名空间中的属性为模型上的属性设置验证规则. using System ...

  8. ASP.NET没有魔法——ASP.NET MVC 模型验证

    在前面的文章中介绍了用户的注册及登录功能,在注册用户时可以通过代码的形式限制用户名及密码的格式,如果不符合要求那么就无法完成操作,如下图: 该功能的原理是Identity基于的Entity Frame ...

  9. 模型验证组件 FluentValidation

    FluentValidation 是 .NET 下的模型验证组件,和 ASP.NET MVC 基于Attribute 声明式验证的不同处,其利用表达式语法链式编程,使得验证组件与实体分开.正如 Flu ...

随机推荐

  1. 3 个用于数据科学的顶级 Python 库

    使用这些库把 Python 变成一个科学数据分析和建模工具. Python 的许多特性,比如开发效率.代码可读性.速度等使之成为了数据科学爱好者的首选编程语言.对于想要升级应用程序功能的数据科学家和机 ...

  2. 29.VUE学习之--键盘事件.键盘修饰符的实例讲解

    键盘事件 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF- ...

  3. Jane Austen【简·奥斯汀】

    Jane Austen Jane Austen, a famous English writer, was born at Steventon, Hampshire, on December 16, ...

  4. [BZOJ1187]神奇游乐园(插头DP)

    Description 题意给定一个矩阵,每个格子有权值,在[-1000.1000]内,求一条回路使得回路经过权值和最大,每个格子最多经过一次 2≤n≤100,2≤m≤6 Code #include ...

  5. 有三个线程T1 T2 T3,如何保证他们按顺序执行

    T3先执行,在T3的run中,调用t2.join,让t2执行完成后再执行t3 在T2的run中,调用t1.join,让t1执行完成后再让T2执行 public class JoinTest {     ...

  6. django 连接MYSQL时,数据迁移时报:django.db.utils.InternalError: (1366, "Incorrect string value: '\\xE9\\x97\\xAE\\xE9\\xA2\\x98' for column 'name' at row 5")

    django 连接MYSQL时,数据迁移时报:django.db.utils.InternalError: (1366, "Incorrect string value: '\\xE9\\x ...

  7. python上数据存储 .h5格式或者h5py

    最近在做城市计算的项目,数据文件是以.h5的格式存储的,总结下其用法和特点 来自百度百科的简介: HDF(Hierarchical Data Format),可以存储不同类型的图像和数码数据的文件格式 ...

  8. MySQL基础4-SQL简单查询(单表)

    1.SELECT语句 2.运算符的优先级 利用Navicat中的查询方法: 栗子1:查询所有货品信息 栗子2:查询所有货品的id,productName,salePrice 当查询错误的时候出现的界面 ...

  9. DEDE调用指定文章ID来调用特定文档

    http://www.jb51.net/cms/137423.html 代码如下: {dede:arclist row=1 idlist='6'} <li><a href=" ...

  10. WWDC2014:留给微软的时间不多了!

    业界定律:第一和第二吵架,最受伤的总是第三名.苹果的wwdc和谷歌io大会的在6月相继召开,结果必然会有一番对比互讽.作为一个曾经的c#程序员,看着在角落里不断划圈圈的微软,心里总是不禁想起那句话:留 ...