Globalizing MVC razor views using cshtml per locale

30. juli 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 18-9-2013 09:04:23 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 23-9-2013 23:54:33 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 4-10-2013 03:44:06 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 5-10-2013 01:56:40 United States #
Handmade Jewelry

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

clicking here... 6-10-2013 00:35:11 United States #
clicking here...

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

Handmade Jewelry 7-10-2013 20:10:11 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 7-10-2013 23:47:07 United States #
Handmade Jewelry

Actually   clear  web internet site , thanks  for this post.

Handmade Jewelry 8-10-2013 03:02:49 United States #
Handmade Jewelry

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

Handmade Jewelry 8-10-2013 22:08:52 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 9-10-2013 04:58:51 United States #
Erasmo Traum

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

google sandbox 12-10-2013 21:03:51 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 14-10-2013 01:28:25 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 12-11-2013 08:18:11 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 12-11-2013 11:56:04 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 20-11-2013 22:39:44 United States #
Bryon Tselee

This really answered my problem, thank you!

Phone Call From Santa Clause 4-12-2013 03:23:09 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 6-12-2013 06:40:22 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 7-12-2013 23:19:20 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 20:18:58 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 15-12-2013 13:16:44 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 17-12-2013 12:22:39 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 20-12-2013 03:10:19 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 21-12-2013 04:39:50 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 19-1-2014 09:31:03 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 6-2-2014 12:12:08 United States #
Shyla

Nice work love what you had to say

voyance 6-2-2014 13:08:32 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 6-2-2014 15:34:44 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 8-2-2014 16:35:08 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 10-2-2014 19:22:45 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 11-2-2014 00:40:15 United States #
http://www.macigarette-electronique.com

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

voyance gratuite immediate 12-2-2014 03:41:34 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 17-2-2014 16:38:43 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 22-2-2014 01:04:17 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 23-2-2014 14:18:29 United States #
diamond

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

jewels advice 23-2-2014 19:47:37 United States #
jewels advice

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

Willena 25-2-2014 13:10:58 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 28-2-2014 05:18:38 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 1-3-2014 10:55:30 United States #
Gisela

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

Tashia 1-3-2014 18:19:13 United States #
Tashia

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

Veda 4-3-2014 06:03:10 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 12-3-2014 01:05:19 United States #
CHAT

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

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

Keep the posts coming it was handy

Brian 10-4-2014 14:29:06 United States #
Brian

Very nice, thanks for the post.

Brian 10-4-2014 17:35:13 United States #
Brian

Very nice, thanks for the post.

Brian 10-4-2014 21:39:10 United States #
Brian

Very nice, thanks for the post.

Brian 10-4-2014 21:43:19 United States #
Brian

Very nice, thanks for the post.

more 7-5-2014 10:14:06 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 15-5-2014 18:55:10 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 19-5-2014 20:20:41 United States #
Felisa

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

these details 1-6-2014 00:02:11 United States #
these details

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

telemainia 5-6-2014 11:28:24 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 18-6-2014 12:43:45 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 15-7-2014 08:37:35 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 6-4-2015 19:43:19 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 14-4-2015 08:10:18 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 16-4-2015 23:46:04 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 29-4-2015 04:30:17 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 15-5-2015 19:09:22 United States #
��C

un site tres bien ficelé

iphone 4s 28-5-2015 02:37:46 United States #
iphone 4s

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

Reina Mcdougald 4-6-2015 09:45:01 United States #
Reina Mcdougald

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

Eva Winford 5-6-2015 17:18:35 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 9-6-2015 12:40:54 United States #
Roxane Ruys

Reading this article - the gift of your time

Margo Blomberg 10-6-2015 11:55:10 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 23-7-2015 11:58:39 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 26-7-2015 01:02:44 United States #
try these guys out

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

Jobstats 27-7-2015 03:05:25 United States #
Jobstats

[...] Trackback [...]

Marco 28-7-2015 20:25:21 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 29-7-2015 03:08:32 United States #
designer bikini

Agua Bendita Acrobacia 6-8-2015 00:37:11 United States #
Agua Bendita Acrobacia

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