C # Enum type Localization

Source: Internet
Author: User
Simple Solution for Enumeration type localization operations, and applied to the dropdownlist of Asp.net MVC. 
 
 
 ///     <Summary>  
/// Enum localizable. Default resouce key = {prefix }_{ Enum}
/// If you ignore prefix, will return {enumtypename }_{ Enum} format
///   </Summary>
[Attributeusage (attributetargets. Enum, allowmultiple =   True , Inherited =   True )]
Public   Class Localizableattribute: attribute
{
Public Localizableattribute (type language)
{
This . Languagetype = Language;
}
Public Localizableattribute (type language, string prefix)
: This (Language)
{
Prefix = Prefix;
}

Public Type required agetype
{
Get ;
Set ;
}
Public   String Prefix
{
Get ;
Set ;
}
}
Public   Static   Class Enumerableextension
{
Public   Static   Void Foreach < T > ( This Ienumerable < T > Enumerable, Action < T > Action)
{
Foreach (T item In Enumerable)
{
Action (item );
}
}

Public   Static   String Tolocalizable ( This Enum value)
{
Localizableattribute customattr = (Localizableattribute) attribute. getcustomattribute (value. GetType (), Typeof (Localizableattribute ));
ResourceManager _ resources =   New ResourceManager (customattr. languagetype );
VaR prefix = Customattr. prefix;
If ( String . Isnullorempty (prefix ))
{
Prefix = Value. GetType (). Name;
}

String Rk = String. Format ( " {0 }_{ 1} " , Prefix, value );
String Localiza = _ Resources. getstring (rk );
If (Localiza =   Null )
{
Return Value. tostring ();
}
Return Localiza;
}

Public   Static Ienumerable < Selectlistitem > Toselectlist ( This Enum enumvalue)
{
Return From Enum E In Enum. getvalues (enumvalue. GetType ())
Select New Selectlistitem {selected = E. Equals (enumvalue), text = Enumerableextension. tolocalizable (E), value = E. tostring ()};
}
} Usage:
 [Localizable (  Typeof  (Corelanguage ),  "  Uesrtitle  "  )]
Public   Enum Usertitle
{
Mr,
Miss
}


// In View
@ Html. dropdownlistfor (M => M. usertitle, model. usertitle. toselectlist (), New {ID =   " Usertitle " })

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.