Introduction
With this tutorial we can show a trouble-free thanks to create localization (globalization) for web application using APS.NET MVC framework. It has to work fine with MVC 1 and a pair of and we're currently using .NET 3.5 SP1, but .NET 4.0 should work too. All code is contained in C# and for language translations we use XML files.
Language files with XML
For translations of various languages we utilize simple xml files. We store them in App_Data/messages/.xml, for example en-US.xml or de-DE.xml. Extremely effective xml structure:
Home
Products
Service
You must have identical language files for all those desired languages. All translation items management of same (with equal "key" attributes).
Create Translator class
Main translation work is going to be made by Translator singleton class. Create "Infrastructure" folder as part of your MVC project and place class Translator there.
First, let's make class singleton:
private static Translator instance = null;
public static Translator Occasion
have
if (instance == null)
instance = new Translator();
return instance;
private Translator()
Add the following fields and properties into the class:
private static string[] cultures = "en-US", "bg-BG" ;
private string locale = string.Empty;
public string Setting
get
if (string.IsNullOrEmpty(locale))
throw new Exception("Locale not set");
also
return locale;
set
if (Cultures.Contains(value))
locale = value;
load();
else
throw new Exception("Invalid locale");
public static string[] Traditions
get
return cultures;
Field "cultures" lists available cultures. "Locale" keeps current culture. In addition to "set" component of Locale property you will see invocation of load() method. We are going to you can talk seriously about the matter later.
To keep localization data I shall create simple dictionary and after that use keys from XML for dictionary keys and XML item values as dictionary values. Simple Translate method do translation job. Now we have Nuclear Link Indexer Review solution to easy accessibility.
private Dictionary data = null;
public string Translate(string key)
if (data != null data.ContainsKey(key))
return data[key];
also
return ":" key ":";
public string this[string key]
receive
return Translate(key);
If some key can't be found and translated, we return the main element with ":" around it, to help you to easy find untranslated items.
Finally, for loading XML we use LINQ to XML. we now have static caching dictionary, i really do not particularly need reading XML on every request.
private static Dictionary> cache =
new Dictionary>();
private void load()
if (cache.ContainsKey(locale) == false) // CACHE MISS !
var doc = XDocument.Load(
HttpContext.Current.Server.MapPath(
"~/App_Data/messages/" locale ".xml"));
cache[locale] = (from item in doc.Descendants("item")
where item.Attribute("key") != null
select latest
Key = item.Attribute("key").Value,
Data = item.Value,
).ToDictionary(i => i.Key, i => i.Data);
data = cache[locale];
public static void ClearCache()
cache = new Dictionary>();
You need to use translator within your controller of this nature:
Translator.Instance[key];
After load() methid now we have ClearCache method for easy developing (you understand, once read, data is cached you have indeed to restart IIS Application Pool to refresh localization data).
Translator class wants, we can allow you to utilize it later.
Create localization helpers
Create static class LocalizationHelpers and set it in "Helpers" folder in the project.
public static string CurrentCulture(this HtmlHelper html)
return Translator.Instance.Locale;
public static string T(this HtmlHelper html, string key)
return html.Encode(Translator.Instance[key]);
public static string T(this HtmlHelper html, string key,
params object[] args)
return html.Encode(string.Format(
Translator.Instance[key], args));
We can use this in html views for translation just
If you would like params in translated values you need to use second T implementation like string.Format. First helper CurrentCulture is used in language select user control to work out current culture.
Create BaseController elegance
Create BaseController class that extends Controller and enter it in "Infrastructure" folder within your MVC project. You ought to extend your complete controller classes out of this class. Create simple property for current selected culture (locale)
public string CurrentCulture
get
return Translator.Instance.Locale;
You ll use both in your controller once you initialize your model, for example.
In the following code I shall explain language detection and saving with cookie.
private void initCulture(RequestContext requestContext)
string cultureCode = getCulture(requestContext.HttpContext);
requestContext.HttpContext.Response.Cookies.Add(
new HttpCookie("Culture", cultureCode)
Expires = DateTime.Now.AddYears(1),
HttpOnly = true,
);
Translator.Instance.Locale = cultureCode;
CultureInfo culture = new CultureInfo(cultureCode);
System.Threading.Thread.CurrentThread.CurrentCulture = culture;
System.Threading.Thread.CurrentThread.CurrentUICulture = culture;
private string getCulture(HttpContextBase context)
string code = getCookieCulture(context);
if (string.IsNullOrEmpty(code))
code = getCountryCulture(context);
return code;
private string getCookieCulture(HttpContextBase context)
HttpCookie cookie = context.Request.Cookies["Culture"];
if (cookie == null ~~ string.IsNullOrEmpty(cookie.Value) ~~
!Translator.Cultures.Contains(cookie.Value))
return string.Empty;
return cookie.Value;
private string getCountryCulture(HttpContextBase context)
// some GeoIp magic here
return "en-US";
First we try to acquire language cookie generally there is any (if such will never be one visit). When there is sadly cookie it is possible to detect browser language, make GeoIP IP address lookup et cetera. After finding some valid locale/culture we set response cookie for next page visits. Following this we change current thread culture. This can be useful if you need to format some date or currency values.
You ought to call initCulture in overridden Initialize method.
Changes in HomeController
Don't forget to change parent class of your controller to BaseController. Add following code in your HomeController, so you can change current culture. When you open specified URL, a cookie is set and user is redirected to index page. This URL is like example.com/home/culture/en-US. Clear cache method is for deleting current cache without restarting application pool. Jump on with example.com/home/ClearLanguageCache
public ActionResult Culture(string id)
HttpCookie cookie = Request.Cookies["Culture"];
cookie.Value = id;
cookie.Expires = DateTime.Now.AddYears(1);
Response.SetCookie(cookie);
return Redirect("/");
public ActionResult ClearLanguageCache(string id)
Translator.ClearCache();
return Redirect("/");
To alter current language we'll create special user control which can be included in may Master.Site layout. Create CultureUserControl.ascx and set it in Views/Shared/ folder of your MVC project. This is actually the code:
en
bg
In our layout we utilize to include it.
Presumption
While in this simple tutorial we've created localization infrastructure for ASP.NET MVC web application. Translations of various languages are saved in XML files. Our team use Translator class to load them. Current user culture is kept in cookie. It is possible to access Translator class in html views saying some helpers. Also every one of the translation data we cached thus it may not be loaded form XML every request.
Hope this tutorial helps.
Precisely what is so wonderful on ASPHostDirectory.com ASP.NET MVC Hosting?
We all know that getting a cheap, reliable web host is not really an easy job so we've put every one of the information you need in a spot for a guide you to make your decision. At ASPHostDirectory, we pride inside ourselves our commitment to our customers and want to verify they have all of the details they are in need of before making that big decision.
We will work tirelessly in terms of a refreshing and friendly grade of customer support. We perceive in creativity, innovation, along with a competitive spirit in many that many of us do. We are sound, honest company who feels that business is more than simply underneath line. We consider every business opportunity an opportunity engage and interact with your customers and our community. Neither our clients nor our employees certainly are a commodity. They're a part of our family.
The followings will be the top 10 reasons you need to trust your online business and hosting must us:
- FREE domain your entire life - ASPHostDirectory provides your individual free domain name always with these Professional Hosting Plan and three free domains with any of Reseller Hosting Plan! There's no should panic about renewing your domain as ASPHostDirectory will automatically do this that you should guarantee you never lose the all important identity within your site
- 99,9% Uptime Guarantee - ASPHostDirectory promises it's customers 99.9% network uptime! We are most certainly so concerned about uptime that many of us setup our own company to observe people's uptime for them called ASPHostDirectory Uptime
- 24/7-based Support - We never sleep off therefore we attempt a service that could be opening 24/7 1 year. Even most people are on holiday during Easter or Christmast/New Year, we're always behind our desk serving you
- Customer Tailored Support - in case you compare our hosting offers to others you will notice that we are offering a superior deal in every aspect; performance, disk quotas, bandwidth allocation, databases, security, user interface features, e-mail services, real-time stats, and maintenance
- Money Back Guarantee - ASPHostDirectory gives a no questions asked' cost refund guarantee for all our plans for any cancellations made within the first 30 days of placing. Our cancellation policy is very simple - should you cancel your account within 60 days of first signing up we can offer you with complete refund
- Experts in ASP.NET MVC Hosting - Because of the scale of our environment, we have recruited and developed the best talent by the hosting technology that you are on the course of using. Our team is strong as a result of the experience and skills of the people who make-up ASPHostDirectory
- Daily Backup Service - We realise that your site is crucial in your business and hence, we never ever forget to produce a daily backup. Your database and website are backup regularly right into a permanent remote tape drive to ensure that they may be always safe and sound. The backup is without doubt ready and available anytime you want it
- Easy Site Administration - With our powerful user interface, you will certainly administer most of your blog post features easily without even requiring you to contact for our particular Support Team. Additionally, you can install in excess of 100 FREE applications directly via our Control Panel approx 1 minute!
Happy Hosting!