简体   繁体   English

如何从Resx中获取文本以在Javascript中使用?

[英]How to get texts from Resx to be used in Javascript?

We are building large ASP.NET applications for the intranet use in multiple languages/cultures. 我们正在构建大型ASP.NET应用程序,以便在多种语言/文化中使用Intranet。 We utilize the Globalization with RESX files and use GetResourceText on the server side to get the localized texts. 我们利用带有RESX文件的Globalization并在服务器端使用GetResourceText来获取本地化文本。

Lately we are doing more and more client side logic with JQuery. 最近我们用JQuery做了越来越多的客户端逻辑。

How do I get the RESX texts to be used in Javascript? 如何在Javascript中使用RESX文本?

  • eg texts used for validation, dynamic messages etc. 例如用于验证的文本,动态消息等。

All our Javascripts are in .JS files, we do not want to mix HTML in the ASPX page and Javascript blocks. 我们所有的Javascripts都在.JS文件中,我们不想在ASPX页面和Javascript块中混合使用HTML。

Thanks for your help. 谢谢你的帮助。

Unfortunately, in an external JS file the server side code is not being processed by the server. 不幸的是,在外部JS文件中,服务器不处理服务器端代码。 However I have seen a workaround where you can set your translated values in hidden fields on the page - this way your javascript will be able to read the values in. 但是我看到了一种解决方法,您可以在页面上的隐藏字段中设置已翻译的值 - 这样您的javascript就能够读取其中的值。

For example: 例如:

 <%-- This goes into your page --%>
 <input type="hidden" id="translatedField" name="translatedField" value="<%=Resources.Resources.translatedText %>" />

and use this inside your javascript file: 并在你的javascript文件中使用它:

 // This is the js file
 $(document).ready(function() {
  alert($("#translatedField").attr("value"));
 });

You will be able to separate the values and still see it in your external JS file. 您将能够分离值并仍然在外部JS文件中看到它。

There is also another workaround that creates a .aspx file that only outputs Javascript instead of HTML. 还有另一种解决方法是创建一个仅输出Javascript而不是HTML的.aspx文件。 Check out the link below: 看看下面的链接:

Using server side method in an external JavaScript file 在外部JavaScript文件中使用服务器端方法

Always separate functionality from human readable strings. 始终将功能与人类可读字符串分开。

If you're creating jQuery-plugins you should be able to pass an array of localized strings as parameter when you call your different jQuery functions. 如果您正在创建jQuery-plugins,那么在调用不同的jQuery函数时,您应该能够将一组本地化字符串作为参数传递。 The array could be defined as inline javascript directly on the page calling the different jQuery plugins or you could load the from external resource in the format /scripts/localization/strings.js?ci=en-US and register a Generic ASP.Net Handler in web.config that would respond to scripts/localization/strings.js 该数组可以直接在调用不同jQuery插件的页面上定义为内联javascript,或者您可以以/scripts/localization/strings.js?ci=en-US格式加载外部资源并注册Generic ASP.Net Handler在web.config中,它将响应scripts/localization/strings.js

The DatePicker control is a fine example of how to localize text for the jQuery datepick control - this js file is dynamically created from resource files (resx) and when included on a page it will make sure the calendar control will have danish text. DatePicker控件是如何本地化jQuery datepick控件的文本的一个很好的例子 - 这个js文件是从资源文件(resx)动态创建的,当它包含在页面上时,它将确保日历控件将具有丹麦文本。

Create a HttpHandler (.ashx file), and return JSON with your text resource strings. 创建一个HttpHandler(.ashx文件),并返回带有文本资源字符串的JSON。

You may also "publish" it to global namespace, ie 您也可以将其“发布”到全局命名空间,即

Response.Write("window.Resources=");
Response.Write((new JavaScriptSerializer()).Serialize(strings));

set up HTML like: 设置HTML像:

<script src="Resx.ashx?lang=en-US" />

<button class="LogoutButtonResourceId OtherButtonClasses">(generic logout text)</button>
<a href="#"><span class="SomeLinkTextResourceId OtherClasses">
     (generic link text)
</span></a>

and apply texts like this: 并应用这样的文字:

$(document).ready(function() {
  for(var resId in Resources){
    $("."+resId).html(Resources[resId]); 
  }
});

I know it's to late but want share my experience in this task) 我知道这是为时已晚,但希望分享我在此任务中的经验)

I use AjaxMin. 我使用AjaxMin。 It can insert resx key values into js file on build event. 它可以在构建事件中将resx键值插入js文件中。 It's not common way but it keeps html without unneeded script blocks and can be done during minification process if you have it. 这不是常见的方式,但它保持html没有不需要的脚本块,并且可以在缩小过程中完成,如果你有它。

It works like this: 它的工作原理如下:

ajaxmin.exe test.js -RES:Strings resource.resx -o test.min.js

Also you need to do the same for ech locale if you have many. 如果你有很多,你也需要为ech语言环境做同样的事情。 Syntax to write resource keys in js (and also css) is written here: 在js(以及css)中写入资源键的语法写在这里:

Js localization Js本地化

Css localization Css本地化

How about injecting it as part of a javascript control initialization? 如何将它作为javascript控件初始化的一部分注入? what i do is as follows: 我做的是如下:

I have a self-contained javascript control - call it CRMControl, which has an init method called setupCRMControl, to which i pass a settings object. 我有一个自包含的javascript控件 - 称之为CRMControl,它有一个名为setupCRMControl的init方法,我传递了一个设置对象。 When i initialize it, i pass an object containing all the resources i need inside javascript as follows: 当我初始化它时,我传递一个包含我在javascript中需要的所有资源的对象,如下所示:

CRMControl.setupCRMControl({
numOfCRMs: 3,
maxNumOfItems: 10,

// then i pass a resources object with the strings i need inside
Resources: {
   Cancel: '@Resources.Cancel',
   Done: '@Resources.Done',
   Title: '@Resources.Title'
 }
});

Then, inside this javascript control: 然后,在这个javascript控件里面:

var crmSettings = {};
this.setupCRMControl(settings) {
    crmSettings = settings;
};

and whenever i want to show a resource, i say (for example, show an alert saying 'Done'): 每当我想要显示资源时,我说(例如,显示一个警告说'完成'):

alert(crmSettings.Resources.Done);

You can call it "R" to make it shorter or something, but this is my approach. 您可以将其称为“R”以缩短或缩短某些内容,但这是我的方法。 Maybe this may not work if you have a whole bunch of strings, but for manageable cases, this may work. 如果你有一大堆字符串,也许这可能不起作用,但对于可管理的情况,这可能有效。

If you don't want to use ASP.NET to generate your main JavaScript, here are two other options: 如果您不想使用ASP.NET生成主JavaScript,则还有以下两个选项:

  1. Use ASP.NET to generate a script file that contains variable-to-string assignments, such as var mystring = 'my value'; 使用ASP.NET生成包含可变到字符串赋值的脚本文件,例如var mystring = 'my value'; . Your main script would then reference the localized text with variables names rather than as embedded values. 然后,您的主脚本将使用变量名称而不是嵌入值来引用本地化文本。 If that's still too "dirty" for you, you could encode the strings as JSON rather than as variable assignments, using an HttpHandler rather than straight .aspx . 如果那对你来说仍然太“脏”,你可以使用HttpHandler而不是直接.aspx将字符串编码为JSON而不是变量赋值。

  2. Have your JavaScript code issue an Ajax call to retrieve an array or list of localized strings from the server. 让您的JavaScript代码发出Ajax调用,以从服务器检索数组或本地化字符串列表。 The server-side part of the call would retrieve the text from your resx files. 调用的服务器端部分将从resx文件中检索文本。

Have you considered using $.ajax in combination with ASP.NET WebMethods? 您是否考虑过将$.ajax与ASP.NET WebMethods结合使用? It's hard to suggest a more concrete solution to this problem without understanding how your JavaScript/jQuery would consume/process the resources. 如果不了解JavaScript / jQuery如何使用/处理资源,很难为这个问题提出更具体的解决方案。 I assume that they're organized into logical groups (or could be) where you could return several resource strings that belong on a single page. 我假设它们被组织成逻辑组(或可能),您可以返回属于单个页面的多个资源字符串。

Assuming that, you could write a very simple C# class -- or use a Dictionary<string, string> -- to return data from your ASP.NET WebMethod. 假设您可以编写一个非常简单的C#类 - 或使用Dictionary<string, string> - 从ASP.NET WebMethod返回数据。 The results would look something like: 结果看起来像:

[WebMethod]
public Dictionary<string, string> GetPageResources(string currentPage)
{
    // ... Organizational stuff goes here.
}

I always separate out my AJAX calls into separate .js files/objects; 我总是把我的AJAX调用分成单独的.js文件/对象; that would look like: 看起来像是这样的:

function GetPageResources (page, callback)
    $.ajax({ // Setup the AJAX call to your WebMethod
        data: "{ 'currentPage':'" + page + "' }",
        url: /Ajax/Resources.asmx/GetPageResources, // Or similar.
        success: function (result) { // To be replaced with .done in jQuery 1.8
            callback(result.d);
        }
    });

Then, in the .js executed on the page, you should be able to consume that data like: 然后,在页面上执行的.js中,您应该能够使用以下数据:

// Whatever first executes when you load a page and its JS files
// -- I assume that you aren't using something like $(document).ready(function () {});
GetPageResources(document.location, SetPageResources);

function SetPageResources(resources) {
    for (currentResource in resources) {
        $("#" + currentResource.Key).html(currentResource.Value);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM