ASP.NET MVC为字段设置多语言显示 [转]

这段时间一直在忙.NET的项目,今天就写一下关于.NET的文章吧,也很长时间没写过.NET的啦 :tongue:

在使用ASP.NET MVC3 的时候,使用元数据模式可以非常方便地设置每个 字段(或者说属性)以减少前台页面代码。如可为 字段 添加验证信息,自定义显示 字段名称等。如以下代码可设置字段显示名称和此字段为必填:






[ DisplayName ( "姓名" ) ] 
[ Required ( ) ] 
Public string Name { get ; set ; } 

//而在View里只需一句话就可以,系统会自动帮你生成验证和字段输入等代码 
@Html . EditorForModel ( ) ;

不需要写一大堆的HTML input等代码,特别是其验证功能感觉很方便,当然你也可以自定义验证错误信息! 

OK,今天主要说说如何在字段属性里动态设置 多语言 。大家看到以上代码是正常写法,只能直接写死某个字段显示的内容,如果要实现 多语言 ,我们就要重写 Display 属性了,只需继承 DisplayNameAttribute 然后就可以将其改写:










10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
22 
23 
24 
25 
26 
27 
public class LocalizedDisplayName : DisplayNameAttribute 

        private string _defaultName = "" ; 

        public Type ResourceType { get ; set ; } 

        public string ResourceName { get ; set ; } 

        public LocalizedDisplayName ( string defaultName ) { _defaultName = defaultName ; } 

        public override string DisplayName 
        { 
            get 
            { 
                PropertyInfo p = ResourceType . GetProperty ( ResourceName ) ; 

                if ( p != null ) 
                { 
                    return p . GetValue ( null , null ) . ToString ( ) ; 
                } 
                else 
                { 
                    return _defaultName ; 
                } 
            } 
        } 
}

以上代码是利用了反射,然后从系统资源里获取相应的语言资源,因此在字段属性里就可以这样使用了:



[ LocalizedDisplayName ( "姓名" , ResourceName = "Name" , ResourceType = typeof ( Resources . Admin ) ) ] 
[ Required ( ) ] 
Public string Name { get ; set ; }

LocalizedDisplayName 的构造函数里有3个参数,分别是默认的语言显示内容,资源名称(一般就是key啦),资源类型(就是你创建的 Resources 的那个类),这样使用起来是否很方便? :smile:

最后顺便说一下,默认情况下直接使用 @Html.EditorForModel(); 出来的字段顺序是与数据库里的排列一致的,就是说如果你之后想为某个表增加一个字段,默认就会显示在页面最下面,这样的话就为界面显示布局带来不便,有时候一些新增的字段不一定就是要放到最后的,解决的办法是可以为每个字段进行 排序 ,只需使用以下代码即可:





[ Display ( Order = 10 ) ] 
Public string Name { get ; set ; } 

[ Display ( Order = 20 ) ] 
Public string Password { get ; set ; }

这样就可为任意字段进行 排序 了 :biggrin:

原文地址:https://www.cnblogs.com/whtydn/p/5305798.html