Click here to Skip to main content
Click here to Skip to main content

Localization with MVC Routes

, 12 Jul 2010 CPOL
Rate this:
Please Sign up or sign in to vote.
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Peki.HR

Croatia Croatia
No Biography provided

Comments and Discussions

 
Questionsource code Pinmemberdeching10-Sep-12 22:11 
GeneralI did something similar. Pinmembervshlos24-Feb-11 21:36 
GeneralMy vote of 2 PinmvpMark Nischalke12-Jul-10 8:36 

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

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

| Advertise | Privacy | Mobile
Web03 | 2.8.141022.2 | Last Updated 12 Jul 2010
Article Copyright 2010 by Peki.HR
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid