Currently I am working on pretty interesting project where if the user is not from the United States but speaks English, I need to present to them an entirely different themed experienced while still providing the same website functionality.
ASP.Net MVC does a very nice thing by encapsulating the view engine code so that is pluggable. As a matter of fact, you can actually use more than one view engine for your website if you wanted, as seen in Scott Hanselman’s post.
In my case, I still want to use the Razor View Engine but I just want to add functionality to dynamically change the paths to the views so that when user hits the web site and their current thread’s UI Culture is say United Kingdom English, I want to point them to an entirely different view engine location where the markup is very different but uses the same model.
Overriding the Razor View Engine
The way to do this is to override the RazorViewEngine class modifying its functions to dynamically change the path based on the current culture.
On every request this request for the view path will first to check to see if the file exists using the FileExists functionion and then if does Exists depending on what type of view request it is, the CreateView, or CreatePartialView will be called. As you can see, I have added functionality to replace the “%G” in the path with what ever the culture is returned from the GetCompCulture function.
All my GetCompCulture function is doing is injection a business object that is getting the users current culture from current thread and then stripping out the “-“ so that “en-US” is “enUS”. It is also defaulting any language culture that we have not set up to also be “enUS”.
Once I have a custom view engine, I just need to tell the MVC framework to only use it instead of the default Razor view engine. I can do that in the application startup event in the Global.cs file.
The Folder Structure
Once my view engine is setup, I then need to setup my folder structure to match. Note, that if you are using a _viewStart.cshtml file, you will need to change the path of the _Layout file in that file.
The folder structure looks something like this.
And that’s it. Your views can now be totally separate and totally different markup based on your language criteria, or any criteria you want to provide for that matter.
Hope that helps.