A technique for localized or enhanced views using ASP.NET MVC 4

Microsoft introduced Display Modes in ASP.NET MVC 4. Display Modes lets an application determine which views to render to the user.

Scott Hanselman has a great post on how to make a switchable Desktop and Mobile sitethat illustrates how to use Display Modes to customize the views for particular mobile browsers by using the User Agent string the browser passes during the request. One of the points that Scott makes in his post is to customize the view that is passed back to the user by changing the ContextCondition evaluated on each request.

This got me thinking about how to use this same technique to render localized content to users. As it turns out it is quite simple, by adding a ContextCondition that checks the default UserLanguage in the Request you can render any localized content. The example that follows checks to see if the user’s default language is Spanish and if so render a view with *.es.cshtml .

DisplayModeProvider.Instance.Modes.Insert(0, new DefaultDisplayMode("es")
{
    ContextCondition = (ctx => ctx.Request.UserLanguages != null && 
        ctx.Request.UserLanguages[0].IndexOf("es", StringComparison.OrdinalIgnoreCase) >= 0)
});

You can extrapolate this technique to display different content for different types of users (standard, premium, etc). The example below will render a *.premium.cshtml view to a user that is determined to be a “premium” user by the IsPremiumUser extension method.

DisplayModeProvider.Instance.Modes.Insert(0, new DefaultDisplayMode("premium")
{
    ContextCondition = (ctx => ctx.IsPremiumUser)
});

Overall I feel like this is a pretty clean way of dealing with these scenarios. Thoughts?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s