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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6465844/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:53:23  来源:igfitidea点击:

How to get texts from Resx to be used in Javascript?

javascriptasp.netresx

提问by PeterFromCologne

We are building large ASP.NET applications for the intranet use in multiple languages/cultures. We utilize the Globalization with RESX files and use GetResourceTexton the server side to get the localized texts.

我们正在构建大型 ASP.NET 应用程序,用于多种语言/文化的 Intranet。我们利用全球化与RESX 文件并在服务器端使用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 文本?

  • e.g. 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.

我们所有的 Javascript 都在 .JS 文件中,我们不想在 ASPX 页面和 Javascript 块中混合使用 HTML。

Thanks for your help.

谢谢你的帮助。

回答by Deano

Unfortunately, in an external JS file the server side code is not being processed by the server. 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.

不幸的是,在外部 JS 文件中,服务器端代码没有被服务器处理。但是,我看到了一种解决方法,您可以在页面上的隐藏字段中设置翻译值 - 这样您的 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. Check out the link below:

还有另一种解决方法可以创建仅输出 Javascript 而不是 HTML 的 .aspx 文件。查看以下链接:

Using server side method in an external JavaScript file

在外部 JavaScript 文件中使用服务器端方法

回答by Pauli ?ster?

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. 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-USand register a Generic ASP.Net Handlerin web.config that would respond to scripts/localization/strings.js

如果您正在创建 jQuery 插件,您应该能够在调用不同的 jQuery 函数时将本地化字符串数组作为参数传递。该数组可以直接在调用不同 jQuery 插件的页面上定义为内联 javascript,或者您可以从外部资源加载格式/scripts/localization/strings.js?ci=en-US并在 web.config 中注册一个通用 ASP.Net 处理程序,该处理程序将响应scripts/localization/strings.js

The DatePickercontrol is a fine example of how to localize text for the jQuery datepick control - this js fileis 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)创建,并包含一个网页时,它会确保日历控件将有丹麦文本。

回答by wizzard0

Create a HttpHandler (.ashx file), and return JSON with your text resource strings.

创建一个 HttpHandler(.ashx 文件),并返回带有文本资源字符串的 JSON。

You may also "publish" it to global namespace, i.e.

您也可以将其“发布”到全局命名空间,即

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]); 
  }
});

回答by jwheron

Have you considered using $.ajaxin combination with 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. 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.

您是否考虑$.ajax过与 ASP.NET WebMethods 结合使用?如果不了解您的 JavaScript/jQuery 将如何消耗/处理资源,就很难为这个问题提出更具体的解决方案。我假设它们被组织成逻辑组(或可能是),您可以在其中返回属于单个页面的多个资源字符串。

Assuming that, you could write a very simple C# class -- or use a Dictionary<string, string>-- to return data from your ASP.NET WebMethod. The results would look something like:

假设这样,您可以编写一个非常简单的 C# 类——或者使用一个Dictionary<string, string>——从您的 ASP.NET WebMethod 返回数据。结果将类似于:

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

I always separate out my AJAX calls into separate .js files/objects; that would look like:

我总是将我的 AJAX 调用分离成单独的 .js 文件/对象;看起来像:

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);
    }
}

回答by Denis Agarev

I know it's to late but want share my experience in this task)

我知道为时已晚,但想分享我在此任务中的经验)

I use AjaxMin. It can insert resx key values into js file on build event. It's not common way but it keeps html without unneeded script blocks and can be done during minification process if you have it.

我使用 AjaxMin。它可以在构建事件中将 resx 键值插入到 js 文件中。这不是常见的方法,但它可以保留 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. Syntax to write resource keys in js (and also css) is written here:

如果你有很多,你也需要对 ech 语言环境做同样的事情。在 js(以及 css)中编写资源键的语法写在这里:

Js localization

JS本地化

Css localization

CSS本地化

回答by Roman Jaquez

How about injecting it as part of a javascript control initialization? what i do is as follows:

将它作为 javascript 控件初始化的一部分注入怎么样?我所做的如下:

I have a self-contained javascript control - call it CRMControl, which has an init method called setupCRMControl, to which i pass a settings object. When i initialize it, i pass an object containing all the resources i need inside javascript as follows:

我有一个独立的 javascript 控件 - 称之为 CRMControl,它有一个名为 setupCRMControl 的 init 方法,我向它传递一个设置对象。当我初始化它时,我传递了一个包含我在 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. Maybe this may not work if you have a whole bunch of strings, but for manageable cases, this may work.

您可以将其称为“R”以使其更短或其他,但这是我的方法。如果您有一大堆字符串,这可能行不通,但对于可管理的情况,这可能行得通。

回答by RickNZ

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';. 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 HttpHandlerrather than straight .aspx.

  2. Have your JavaScript code issue an Ajax call to retrieve an array or list of localized strings from the server. The server-side part of the call would retrieve the text from your resx files.

  1. 使用 ASP.NET 生成包含变量到字符串赋值的脚本文件,例如var mystring = 'my value';. 然后,您的主脚本将使用变量名称而不是嵌入值来引用本地化文本。如果这仍然太“脏”你,你可以编码字符串作为JSON,而不是作为变量赋值,使用HttpHandler而不是直线.aspx

  2. 让您的 JavaScript 代码发出 Ajax 调用以从服务器检索一个数组或本地化字符串列表。调用的服务器端部分将从您的 resx 文件中检索文本。