Welcome to MSDN Blogs Sign in | Join | Help

Syndication

News

Localized Javascript Resources with MVC
We needed to have a handful of localized strings available to javascript. A simple but effective approach we're taking with asp.net mvc is adding a route such as this:
routes.MapRoute("ScriptResources", "res/resources.js", new { controller = "System", action = "ScriptResources" });

The controller simply calls View("Resources") and the View creates a simple json object like this
ForumsRes = 
{
    prompt_clearAbuseReason: <%= AntiXss.JavaScriptEncode(Resource.prompt_clearAbuseReason) %>,
    prompt_deleteReason: <%= AntiXss.JavaScriptEncode(Resource.prompt_deleteReason) %>,
    prompt_pageExit: <%= AntiXss.JavaScriptEncode(Resource.prompt_pageExit) %>,
    prompt_reportAbuseReason: <%= AntiXss.JavaScriptEncode(Resource.prompt_reportAbuseReason) %>,
    prompt_stickyUntil: <%= AntiXss.JavaScriptEncode(Resource.prompt_stickyUntil) %>,
    prompt_undeleteReason: <%= AntiXss.JavaScriptEncode(Resource.prompt_undeleteReason) %>,
    rte_alreadyOpen: <%= AntiXss.JavaScriptEncode(Resource.rte_alreadyOpen) %>
}

The web page can include it like any other script and reference a loc string like ForumsRes.rte_alreadyOpen. Another nice thing is you can easily OutputCache this too.

Simple idea, but thought it was worth sharing.

Published Thursday, March 12, 2009 7:13 AM by RobJ

Filed under: , ,

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# ASP.NET MVC Archived Buzz, Page 1 @ Thursday, March 12, 2009 3:37 AM

PingBack from http://aspdotnetmvc.com/buzz/default.aspx

ASP.NET MVC Archived Buzz, Page 1

# ASP.NET MVC Archived Buzz, Page 1 @ Thursday, March 12, 2009 3:37 AM

PingBack from http://aspdotnetmvc.com/buzz/default.aspx

ASP.NET MVC Archived Buzz, Page 1

# re: Localized Javascript Resources with MVC @ Thursday, February 11, 2010 5:16 PM

Thanks for sharing this. What else is in your Resources view? I am seeing the following error:

MasterPage cannot be applied to this page because the control collection is read-only. If the page contains code blocks, make sure they are placed inside content controls (i.e. <asp:Content runat=server />)

My view looks like:

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>

<%@ OutputCache Duration="10000" VaryByParam="none" %>

ForumsRes =

{

   gdict_AddNew: <%= Resources.App.AddNew %>,

   gdict_DateCreated: <%= Resources.App.DateCreated%>

}

Thanks

Kevin

Leave a Comment

(required) 
required 
(required) 

  
Enter Code Here: Required
© 2010 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement  
Page view tracker