how to read resource file in jquery or javascript or js file

As generally we do in asp.net project, I have created a global resource file for storing common error messages, info messages, labels etc in my first MVC4 project. I used ready-made validation.js for giving validation. I have face the problem how to get the resource file’s object value in .js file. From come out this problem I have find a way. I had create a controller ‘ResoruceScript’. And added below code in ActionResult method.

        public ActionResult Index()
        {
            Response.Clear();            
            Response.ContentType = "text/javascript";
            
            return View();
        }

Then create a view for “Index” Action. And remove the html content, all tags which are added by default when we create a new view. And below code.


        @using System.Collections
@using System.Globalization
@using System.Resources
@using Pharma
@{
    Layout = null;
    // Get a set of resources appropriate to the culture defined by the browser
    ResourceSet resourceSet = @Resources.PharmaCore.ResourceManager.GetResourceSet
        (CultureInfo.CurrentUICulture, true, true);
}

// Define the empty object in javascript
var Resources = {};
@foreach (DictionaryEntry res in resourceSet)
{
    // Create a property on the javascript object for each text resource
    @:Resources.@res.Key = "@Html.Raw(
        HttpUtility.JavaScriptStringEncode(res.Value.ToString()))";
}

Here, PharmaCore is my resource file name. Above code create the array of resource file’s objects. Add this view as javascript file in head tag or anywhere in the page but before the use of resource value. I have added in head tag of page.

 <script src="~/ResourceScript"&gtl</script>

Now, you are able to get the resource file’s object value as ‘Resources.rfv_Common_Msg’ in .js file.

Share