Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Localization with MVC Routes

0.00/5 (No votes)
12 Jul 2010 1  
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:

' 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:

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.

<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:

<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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here