Globalizing MVC razor views using cshtml per locale

30. July 2013 21:33 by martijn in .net, globalization, MVC

There are quite a few ways to localize your MVC applications. The best is probably to reference resources (resx) from your cshtml files. For a overview see this complete guide and the post by Hanselman

This can be a bit awkward though if you need a different structure for a different country. Another option is to use a cshtml file per locale. For example use a index.nl.cshtml file for dutch users and index.cshtml for other users. How to do this is the topic of this post. Be aware that this should not be your first choice because you basically copy your HTML making changes later on harder. It can be good to know this trick sometimes... (If you use WebForms viewengine you should use this guide.)


To get this working we need to complete a few steps

  1. Create a localized view
  2. Create a viewengine that prefers localized views and uses the default view if none is found. This makes localization optional and nice to combine with other (resource based) solutions.
  3. Register the ViewEngine in global.asax

Create a localized view

How you structure your views is arbitrary. For this post I post the localized direct next to the normal view. Here I created a Index for the dutch (nl) locale:

Creating the globalized ViewEngine

We subclass the normal RazorViewEngine and only change the part that determines which file is used. We use the CurrentUICulture of the current thread to determine which culture should be used. Then we check to see if there is a view specific for this culture. If no specific view is found the regular view is used.

using System;
using System.IO;
using System.Web.Mvc;
namespace LocalizedViews
{
public sealed class RazorGlobalizationViewEngine : RazorViewEngine
{
protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath)
{
partialPath = GlobalizeViewPath(controllerContext, partialPath);
return base.CreatePartialView(controllerContext, partialPath);
}
protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath)
{
viewPath = GlobalizeViewPath(controllerContext, viewPath);
return base.CreateView(controllerContext, viewPath, masterPath);
}
private static string GlobalizeViewPath(ControllerContext controllerContext, string viewPath)
{
var request = controllerContext.HttpContext.Request;
var lang = System.Threading.Thread.CurrentThread.CurrentUICulture.Name;
if (!string.IsNullOrEmpty(lang) && !string.Equals(lang, "en", StringComparison.InvariantCultureIgnoreCase))
{
string localizedViewPath = viewPath.Replace(".cshtml", "." + lang + ".cshtml");
if (File.Exists(request.MapPath(localizedViewPath)))
{
viewPath = localizedViewPath;
}
}
return viewPath;
}
}
}

Registering the ViewEngine in global.asax

We can register the viewengine in the global asax like this:

 protected void Application_Start()

        {

            ViewEngines.Engines.Clear();

            ViewEngines.Engines.Add(new RazorGlobalizationViewEngine());

           //the rest of it..

        }

And that's all there is too it. Happy coding!

click this 9/18/2013 9:04:23 AM United States #
click this

Hi, Neat post. There is a problem with your web site in web explorer, could test this� IE nonetheless is the marketplace chief and a large portion of folks will pass over your great writing due to this problem.

Handmade Jewelry 9/23/2013 11:54:33 PM United States #
Handmade Jewelry

i joined so numerous seo forum on the internet and they are truly quite useful and i have learned a good deal,

Copper Jewelry 10/4/2013 3:44:06 AM United States #
Copper Jewelry

Naturally I like your web-site, nonetheless you need to have to check the spelling on several of your posts. Many of them are rife with spelling difficulties and I discover it extremely silly to inform you. On the other hand I will surely come once more again!

Handmade Jewelry 10/5/2013 1:56:40 AM United States #
Handmade Jewelry

Vi ringrazio, ho trovato che  quanto scritto non sia completamente corretto

clicking here... 10/6/2013 12:35:11 AM United States #
clicking here...

I always was concerned in this subject and stock still am, regards for posting.

Handmade Jewelry 10/7/2013 8:10:11 PM United States #
Handmade Jewelry

Nice post. I learn some thing tougher on distinct blogs everyday. Most commonly it truly is stimulating to learn to read content from other writers and exercise a specific thing there. I�d would rather use some together with the content material in my weblog no matter whether you don�t mind. Natually I�ll offer you with a link in your web weblog. A lot of thanks for sharing.

Handmade Jewelry 10/7/2013 11:47:07 PM United States #
Handmade Jewelry

Actually   clear  web internet site , thanks  for this post.

Handmade Jewelry 10/8/2013 3:02:49 AM United States #
Handmade Jewelry

I like this  web website really significantly, Its a  truly  nice  billet  to read and  obtain  info  .

Handmade Jewelry 10/8/2013 10:08:52 PM United States #
Handmade Jewelry

I’m impressed, I must say. Truly rarely do I encounter a weblog that’s both educative and entertaining, and let me let you know, you might have hit the nail on the head. Your thought is outstanding; the problem is something that not enough individuals are speaking intelligently about. I'm very pleased that I stumbled across this in my search for something relating to this.

Erasmo Traum 10/9/2013 4:58:51 AM United States #
Erasmo Traum

Hey check this new project http://projectalfa.ueuo.com/

google sandbox 10/12/2013 9:03:51 PM United States #
google sandbox

This is the right blog for anyone who wants to find out about this topic. You realize so much its almost hard to argue with you (not that I actually would want�HaHa). You definitely put a new spin on a topic thats been written about for years. Great stuff, just great!

Copper Jewelry 10/14/2013 1:28:25 AM United States #
Copper Jewelry

Sweet weblog! I found it even though browsing on Yahoo News. Do you have any suggestions on how to get listed in Yahoo News? I’ve been trying for a although but I never seem to get there! Thank you

Welding Machines 11/12/2013 8:18:11 AM United States #
Welding Machines

I need to to express back to you you have certainly helped us by simply writing this unique content. I was happy to use your subsequently handy information and facts and set it to a lot of fantastic use. I would like to express our gratitude and want to inform your visitors that they're so blessed to have someone just like you making fantastic articles. I actually anticipate reading much more helpful content like this from you down the road. Once again, many thanks so much with the very helpful blog post. I have added your feed and book-marked you site within my social bookmarking website. Cheers!

Mikki Wehrly 11/12/2013 11:56:04 AM United States #
Mikki Wehrly

Not one comment?  I feel as though I'm one who is on the fence in this area of thought. The fence, that is, of actually understanding this, and those considered Luddites by the former group. There are enough scenarios left out of this eye-opening article, that yes, another trilogy of sci-fi "Imagine a whole world where . . . ." type movies could be made.

Bryon Tselee 11/20/2013 10:39:44 PM United States #
Bryon Tselee

This really answered my problem, thank you!

Phone Call From Santa Clause 12/4/2013 3:23:09 AM United States #
Phone Call From Santa Clause

Hmm is anyone else having problems with the images on this blog loading? I'm trying to figure out if its a problem on my end or if it's the blog. Any feedback would be greatly appreciated.

Santa Phone Call 12/6/2013 6:40:22 AM United States #
Santa Phone Call

Wow that was odd. I just wrote an really long comment but after I clicked submit my comment didn't show up. Grrrr... well I'm not writing all that over again. Anyhow, just wanted to say wonderful blog!

Santa letters 12/7/2013 11:19:20 PM United States #
Santa letters

Howdy! Quick question that's entirely off topic. Do you know how to make your site mobile friendly? My website looks weird when viewing from my iphone. I'm trying to find a template or plugin that might be able to correct this problem. If you have any suggestions, please share. Thanks!

Rayna 12/12/2013 8:18:58 PM United States #
Rayna

I wish to express some thanks to the writer just for rescuing me from this particular trouble. Right after scouting throughout the the web and meeting ideas which were not pleasant, I believed my life was gone. Being alive devoid of the strategies to the problems you've fixed by way of your good guideline is a crucial case, and the kind that might have in a negative way affected my entire career if I had not encountered your web site. Your own capability and kindness in controlling every part was priceless. I don't know what I would've done if I hadn't come upon such a solution like this. I can also at this moment relish my future. Thank you very much for your skilled and sensible help. I won't be reluctant to recommend the website to anybody who should get tips on this subject.

Restaurant Equipment 12/15/2013 1:16:44 PM United States #
Restaurant Equipment

I have been browsing on-line greater than 3 hours as of late, but I never discovered any attention-grabbing article like yours. It is beautiful price sufficient for me. In my view, if all website owners and bloggers made good content material as you probably did, the internet will be much more helpful than ever before.|

Custom Printed Boxes 12/17/2013 12:22:39 PM United States #
Custom Printed Boxes

Hola! I've been following your web site for a while now and finally got the bravery to go ahead and give you a shout out from  Huffman Tx! Just wanted to say keep up the excellent job!|

Sha 12/20/2013 3:10:19 AM United States #
Sha

Hello! I know this is kind of off topic but I was wondering if you knew where I could find a captcha plugin for my comment form? I'm using the same blog platform as yours and I'm having trouble finding one? Thanks a lot!

his comment is here 12/21/2013 4:39:50 AM United States #
his comment is here

You are my aspiration, I possess few web logs and rarely run out from post Smile. "Analyzing humor is like dissecting a frog. Few people are interested and the frog dies of it." by E. B. White.

http://is.gd/RW81cM 1/19/2014 9:31:03 AM United States #
http://is.gd/RW81cM

I just could not depart your site before suggesting that I extremely enjoyed the standard info an individual supply on your visitors? Is gonna be back regularly in order to check up on new posts.

Shyla 2/6/2014 12:12:08 PM United States #
Shyla

Nice work love what you had to say

voyance 2/6/2014 1:08:32 PM United States #
voyance

tirage tarot par telephone nice<br/>Consulter mon superbe site : <a href="http://www.paradiseradio;fr">voyance gratuite en ligne</a>

Extra voyance 2/6/2014 3:34:44 PM United States #
Extra voyance

voyance gratuite en direct de marseille<br/>Voir notre magnifique post : <a href="http://www.paradiseradio;fr">voyance en direct</a>

voyance sans attendre 2/8/2014 4:35:08 PM United States #
voyance sans attendre

tirage voyance par mail nice<br/>Visiter le nouveau site : <a href="http://paradiseradio.fr">voyance par telephone gratuite</a>

http://www.paradiseradio.fr 2/10/2014 7:22:45 PM United States #
http://www.paradiseradio.fr

consulter tarot par fax perpignan<br/>Voir notre excellent blog : <a href="http://www.paradiseradio;fr">voyance gratuite en ligne</a>

http://www.macigarette-electronique.com 2/11/2014 12:40:15 AM United States #
http://www.macigarette-electronique.com

Voir le magnifique site : <a href="macigarette-electronique.com">Acheter liquide ecigarette</a><br/>

voyance gratuite immediate 2/12/2014 3:41:34 AM United States #
voyance gratuite immediate

consultation voyance en ligne perpignan<br/>Voir le superbe post : <a href="http://paradiseradio.fr">voyance gratuite en direct</a>

hostingoweseo.org 2/17/2014 4:38:43 PM United States #
hostingoweseo.org

Hi, I do think this is an excellent site. I stumbledupon it I am going to come back once again since i have book-marked it. Money and freedom is the greatest way to change, may you be rich and continue to guide other people.

free for iphone 2/22/2014 1:04:17 AM United States #
free for iphone

nice share,Thanks for the informations dont forget to drop by my link and apply to be able to win a free iphone 5c https://www.youtube.com/watch?v=Sp3wOejk52I

diamond 2/23/2014 2:18:29 PM United States #
diamond

Keep the practical post coming, I have actually been able to get exactly what I required from it.

jewels advice 2/23/2014 7:47:37 PM United States #
jewels advice

I love your presentation, keep composing a providing info like this.

Willena 2/25/2014 1:10:58 PM United States #
Willena

Sometimes it seems like the information you need isn't out there, then you find a blog like yours, Thank for sharing.

helpful site 2/28/2014 5:18:38 AM United States #
helpful site

I think this is among the most significant info for me. And i am glad reading your article. But should remark on few general things, The site style is great, the articles is really great : D. Good job, cheers

Gisela 3/1/2014 10:55:30 AM United States #
Gisela

This information is very useful, thanks for the research that you have done.

Tashia 3/1/2014 6:19:13 PM United States #
Tashia

It was my pleasure finding your blog, please keep providing such useful information.

Veda 3/4/2014 6:03:10 AM United States #
Veda

Sometimes it seems like the information you need isn't out there, then you find a blog like yours, Thank for sharing.

CHAT 3/12/2014 1:05:19 AM United States #
CHAT

Very interesting information!Perfect just what I was searching for!

teeth whitening 3/22/2014 11:43:32 AM United States #
teeth whitening

Keep the posts coming it was handy

Brian 4/10/2014 2:29:06 PM United States #
Brian

Very nice, thanks for the post.

Brian 4/10/2014 5:35:13 PM United States #
Brian

Very nice, thanks for the post.

Brian 4/10/2014 9:39:10 PM United States #
Brian

Very nice, thanks for the post.

Brian 4/10/2014 9:43:19 PM United States #
Brian

Very nice, thanks for the post.

more 5/7/2014 10:14:06 AM United States #
more

Enjoyed  reading through  this, very good stuff,  regards . "Love begets love, love knows no rules, this is the same for all." by Virgil.

see this site 5/15/2014 6:55:10 PM United States #
see this site

Utterly composed content, thanks for selective information. "The bravest thing you can do when you are not brave is to profess courage and act accordingly." by Corra Harris.

Felisa 5/19/2014 8:20:41 PM United States #
Felisa

Good to see information that can help me is still online.

these details 6/1/2014 12:02:11 AM United States #
these details

Very interesting  subject , thanks  for posting . "Time flies like an arrow. Fruit flies like a banana." by Lisa Grossman.

telemainia 6/5/2014 11:28:24 AM United States #
telemainia

Magnificent web site. Lots of useful information here. I am sending it to several pals ans also sharing in delicious. And of course, thank you for your effort!

Pantofi Barbatesti 6/18/2014 12:43:45 PM United States #
Pantofi Barbatesti

Considering that I to begin with wrote in excess of MBT footwear at <strong><a href="incaltaminte-mopiel.ro/.../category&path=18_46"; title="Pantofi Barbatesti">Pantofi Barbatesti</a></strong>, a ton consists of altered around the manufacturer, and the inventor and founder is made up of still left the business enterprise. Concerning true purchasers, evaluations of MBT sneakers are pretty put together. If your self're taking into consideration a few of MBT footwear, I strongly inspire yourself towards in addition study the suggestions remaining in just answer in the direction of the immediately after posts, and communicate in the direction of your health practitioner prior to sporting any design of shoe that is consequently considerably alternate in opposition to what by yourself're made use of toward, or toward address any model of ache or situation.

Tuner analogowy cena 7/15/2014 8:37:35 AM United States #
Tuner analogowy cena

Magnificent site. A lot of useful information here. I am sending it to a few friends ans also sharing in delicious. And naturally, thanks for your sweat!

Leo Carota 4/6/2015 7:43:19 PM United States #
Leo Carota

Hello would you mind sharing which blog platform you're using? I'm planning to start my own blog in the near future but I'm having a tough time choosing between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your design and style seems different then most blogs and I'm looking for something unique. P.S Apologies for getting off-topic but I had to ask!

Louann Battersby 4/14/2015 8:10:18 AM United States #
Louann Battersby

Howdy I am so glad I found your website, I really found you by accident, while I was looking on Bing for something else, Anyhow I am here now and would just like to say thanks for a remarkable post and a all round enjoyable blog (I also love the theme/design), I don't have time to read through it all at the moment but I have bookmarked it and also added in your RSS feeds, so when I have time I will be back to read more, Please do keep up the awesome work.

Terisa Jory 4/16/2015 11:46:04 PM United States #
Terisa Jory

Hello! Do you know if they make any plugins to safeguard against hackers? I'm kinda paranoid about losing everything I've worked hard on. Any recommendations?

Dropbox Tips Tricks 4/29/2015 4:30:17 AM United States #
Dropbox Tips Tricks

You ought to take part in a contest for one of the most useful sites on the net. I most certainly will recommend this web site!

��C 5/15/2015 7:09:22 PM United States #
��C

un site tres bien ficelé

iphone 4s 5/28/2015 2:37:46 AM United States #
iphone 4s

<p>Dead composed subject material, Really enjoyed looking through.</p>

Reina Mcdougald 6/4/2015 9:45:01 AM United States #
Reina Mcdougald

I will not speak about your competence, the write-up simply disgusting

Eva Winford 6/5/2015 5:18:35 PM United States #
Eva Winford

Hello would you mind stating which blog platform you're using? I'm looking to start my own blog in the near future but I'm having a difficult time selecting between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your design seems different then most blogs and I'm looking for something completely unique.                  P.S My apologies for being off-topic but I had to ask!

Roxane Ruys 6/9/2015 12:40:54 PM United States #
Roxane Ruys

Reading this article - the gift of your time

Margo Blomberg 6/10/2015 11:55:10 AM United States #
Margo Blomberg

Hello! I just wanted to ask if you ever have any trouble with hackers? My last blog (wordpress) was hacked and I ended up losing several weeks of hard work due to no back up. Do you have any methods to protect against hackers?

renewable energy devices townsville 7/23/2015 11:58:39 AM United States #
renewable energy devices townsville

Thank you for producing such a valuable article. I think this is the most engaging material on this subject I've ever read. You've done some deep research and great writing. This is impressive, quality work.

try these guys out 7/26/2015 1:02:44 AM United States #
try these guys out

I've a few question to you, publish to those I do not e-mail

Jobstats 7/27/2015 3:05:25 AM United States #
Jobstats

[...] Trackback [...]

Marco 7/28/2015 8:25:21 PM United States #
Marco

32 Now learn a parable of the fig tree; When his branch is yet tender, and putteth forth leaves, ye know that summer is nigh: 33 So likewise ye, when ye shall see all these things, know that it is near, even at the doors. 34 Verily I say unto you, This generation shall not pass, till all these things be fulfilled. 35 Heaven and earth shall pass away, but my words shall not pass away. 36 But of that day and hour knoweth no man, no, not the angels of heaven, but my Father only. 37 But as the days of Noe were, so shall also the coming of the Son of man be. 38 For as in the days that were before the flood they were eating and drinking, marrying and giving in marriage, until the day that Noe entered into the ark, 39 And knew not until the flood came, and took them all away; so shall also the coming of the Son of man be. 40 Then shall two be in the field; the one shall be taken, and the other left. 41 Two women shall be grinding at the mill; the one shall be taken, and the other left. 42 Watch therefore: for ye know not what hour your Lord doth come. 43 But know this, that if the goodman of the house had known in what watch the thief would come, he would have watched, and would not have suffered his house to be broken up. 44 Therefore be ye also ready: for in such an hour as ye think not the Son of man cometh.

designer bikini 7/29/2015 3:08:32 AM United States #
designer bikini

Agua Bendita Acrobacia 8/6/2015 12:37:11 AM United States #
Agua Bendita Acrobacia

I  conceive you have  noted  some very interesting  details ,  thankyou  for the post.