zoukankan      html  css  js  c++  java
  • 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:

  • 相关阅读:
    Linux下Tomcat启动、停止、重新启动
    Linux安装Tomcat
    CentOS7防火墙firewalld 和 CentOS6防火墙iptables的一些配置命令
    Zabbix监控报警Lack of free swap space on Zabbix server解决办法
    CentOS7 防火墙firewalld 和 CentOS6 防火墙iptables 开放zabbix-agent端口的方法
    yii2安装配置完成后,网页打开报错yiiwebRequest::cookieValidationKey must be configured with a secret key
    CentOS 7 使用unzip解压zip文件提示未找到命令的解决方法
    docker安装脚本
    hadoop常用命令
    yum常用安装包
  • 原文地址:https://www.cnblogs.com/whtydn/p/5305798.html
Copyright © 2011-2022 走看看