Click here to Skip to main content
15,868,033 members
Articles / Web Development / HTML

Localization with MVC Routes

Rate me:
Please Sign up or sign in to vote.
4.00/5 (2 votes)
12 Jul 2010CPOL2 min read 26.4K   8   4
Simple and efficient way to localize MVC websites using routes

Introduction

This tutorial will help you localize your MVC applications using routes as base values for language selection.

Do the Basics

Create a new MVC2 application. This is the project structure that you will get:

Proj1

Now to localize your application, you simply create the special App_GlobalResources folder and create two or more Resource files for your strings, and change the values:

The Code

In order for localization to work, we will have to modify the default route a bit, add a language parameter in front of route URL and modify the defaults so the language is set to users default Windows language:

VB.NET
' Note: For instructions on enabling IIS6 or IIS7 classic mode, 
' visit http://go.microsoft.com/?LinkId=9394802
 
Public Class MvcApplication
    Inherits System.Web.HttpApplication
 
    Shared Sub RegisterRoutes(ByVal routes As RouteCollection)
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}")
        ' MapRoute takes the following parameters, in order:
        ' (1) Route name
        ' (2) URL with parameters
        ' (3) Parameter defaults
        routes.MapRoute("Default", "{language}/{controller}/{action}/{id}",
                        New With {.language = My.Application.Culture.Name,
                                  .controller = "Home",
                                  .action = "Index",
                                  .id = UrlParameter.Optional})
    End Sub
 
    Sub Application_Start()
        AreaRegistration.RegisterAllAreas()
        RegisterRoutes(RouteTable.Routes)
    End Sub
 
End Class

Next, to tell our controllers to read those route values and change Culture and UICulture according to the route values, we will have to create a Class that will inherit from base controller and override its OnActionExecuting method:

VB.NET
Public Class GlobalController
    Inherits System.Web.Mvc.Controller
 
    Protected Overrides Sub OnActionExecuting_
	(ByVal filterContext As System.Web.Mvc.ActionExecutingContext)
        MyBase.OnActionExecuting(filterContext)
        If RouteData.Values.First.Value IsNot Nothing Then
            Try
                My.Application.ChangeCulture(RouteData.Values.First.Value)
                My.Application.ChangeUICulture(RouteData.Values.First.Value)
            Catch ex As Globalization.CultureNotFoundException
                My.Application.ChangeCulture("en-US")
                My.Application.ChangeUICulture("en-US")
            End Try
        End If
    End Sub
 
End Class

The method will do the same as the original and also read 1st route value for the language string, for example:

http://localhost:55308/hr-HR/Home/About will attempt to read Croatian resource file, and if the route value is a bogus value, it will revert back to English.

Now for all of this to work, all your controllers will have to inherit from GlobalController, so we change the HomeController accordingly, and also print out the default welcome message through Resources.Strings.

VB.NET
<HandleError()> _
Public Class HomeController
    Inherits GlobalController
 
    Function Index() As ActionResult
        ViewData("Message") = Resources.Strings.WelcomeText
        Return View()
    End Function
 
    Function About() As ActionResult
        ViewData("Message") = Resources.Strings.AboutText
        Return View()
    End Function
 
End Class

So to recap, this will now based on your Windows language change the Culture for your application, but what about manual change?!

To do that we can add a combobox, some flags or just two basic links to the master page to switch the language route value:

ASP.NET
<ul id="menu">              
  <li><%: Html.ActionLink("Hrvatski", 
	My.Request.RequestContext.RouteData.Values.ElementAt(2).Value.ToString, 
	New With {.language = "hr-HR"})%></li>
  <li><%: Html.ActionLink("English", 
	My.Request.RequestContext.RouteData.Values.ElementAt(2).Value.ToString, 
	New With {.language = "en-US"})%></li>
</ul>

Conclusion

The Culture and UICulture settings are not stored in session, or storage or anywhere else, it simply works through the URL route. The menu items and buttons don't have hardcoded links and switching is made super easy.

I hope this article helps you to do localization the MVC way. I'm also open to suggestions and improvements.

History

  • 12th July, 2010: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Croatia Croatia
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionImages not loading Pin
satyajit mohanta25-Jun-15 3:57
satyajit mohanta25-Jun-15 3:57 
Questionsource code Pin
deching10-Sep-12 22:11
deching10-Sep-12 22:11 
GeneralI did something similar. Pin
vshlos24-Feb-11 21:36
vshlos24-Feb-11 21:36 
GeneralMy vote of 2 Pin
Not Active12-Jul-10 8:36
mentorNot Active12-Jul-10 8:36 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.