Use ASP.NET Resource strings from within javascript files

后端 未结 9 1703
迷失自我
迷失自我 2020-12-13 01:02

How would one get resx resource strings into javascript code stored in a .js file?

If your javascript is in a script block in the markup, you can use this syntax:

相关标签:
9条回答
  • 2020-12-13 01:26

    use a hidden field to hold the resource string value and then access the field value in javascript for example : " />

    var todayString= $("input[name=TodayString][type=hidden]").val();

    0 讨论(0)
  • 2020-12-13 01:29

    Add the function in the BasePage class:

        protected string GetLanguageText(string _key)
        {
            System.Resources.ResourceManager _resourceTemp = new System.Resources.ResourceManager("Resources.Language", System.Reflection.Assembly.Load("App_GlobalResources"));
            return _resourceTemp.GetString(_key);
        }
    

    Javascript:

        var _resurceValue = "<%=GetLanguageText("UserName")%>";
    

    or direct use:

        var _resurceValue = "<%= Resources.Language.UserName %>";
    

    Note: The Language is my resouce name. Exam: Language.resx and Language.en-US.resx

    0 讨论(0)
  • 2020-12-13 01:31

    Here is my solution for now. I am sure I will need to make it more versatile in the future... but so far this is good.

    using System.Collections;
    using System.Linq;
    using System.Resources;
    using System.Web.Mvc;
    using System.Web.Script.Serialization;
    
    public class ResourcesController : Controller
    {
        private static readonly JavaScriptSerializer Serializer = new JavaScriptSerializer();
    
        public ActionResult GetResourcesJavaScript(string resxFileName)
        {
            var resourceDictionary = new ResXResourceReader(Server.MapPath("~/App_GlobalResources/" + resxFileName + ".resx"))
                                .Cast<DictionaryEntry>()
                                .ToDictionary(entry => entry.Key.ToString(), entry => entry.Value.ToString());
            var json = Serializer.Serialize(resourceDictionary);
            var javaScript = string.Format("window.Resources = window.Resources || {{}}; window.Resources.{0} = {1};", resxFileName, json);
    
            return JavaScript(javaScript);
        }
    
    }
    
    // In the RegisterRoutes method in Global.asax:
    routes.MapRoute("Resources", "resources/{resxFileName}.js", new { controller = "Resources", action = "GetResourcesJavaScript" });
    

    So I can do

    <script src="/resources/Foo.js"></script>
    

    and then my scripts can reference e.g. window.Resources.Foo.Bar and get a string.

    0 讨论(0)
提交回复
热议问题