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

发布于 2024-11-16 21:15:52 字数 339 浏览 6 评论 0原文

我们正在构建大型 ASP.NET 应用程序,以便在多种语言/文化中使用 Intranet。我们利用 RESX 文件的全球化,并在服务器端使用 GetResourceText 来获取本地化文本。

最近我们用 JQuery 做越来越多的客户端逻辑。

如何获取要在 Javascript 中使用的 RESX 文本?

  • 例如用于验证、动态消息等的文本。

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

感谢您的帮助。

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

Lately we are doing more and more client side logic with JQuery.

How do I get the RESX texts to be used in Javascript?

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

Thanks for your help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

長街聽風 2024-11-23 21:15:52

不幸的是,在外部 JS 文件中,服务器端代码没有被服务器处理。不过,我看到了一种解决方法,您可以在页面上的隐藏字段中设置翻译后的值 - 这样您的 javascript 将能够读取其中的值。

例如:

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

并在您的 javascript 文件中使用它:

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

您将能够分离值,并且仍然可以在外部 JS 文件中看到它。

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

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

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.

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:

 // 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.

There is also another workaround that creates a .aspx file that only outputs Javascript instead of HTML. Check out the link below:

Using server side method in an external JavaScript file

感悟人生的甜 2024-11-23 21:15:52

始终将功能与人类可读的字符串分开。

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

DatePicker 控件是一个如何本地化 jQuery datepick 控件文本的好示例 - this js 文件 是从资源文件 (resx) 动态创建的,当包含在页面上时,它将确保日历控件将具有丹麦语文本。

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-US and register a Generic ASP.Net Handler in web.config that would respond to 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.

笑叹一世浮沉 2024-11-23 21:15:52

创建 HttpHandler(.ashx 文件),并使用文本资源字符串返回 JSON。

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

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

设置 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>

并应用如下文本:

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

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

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

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

set up HTML like:

<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]); 
  }
});
余生共白头 2024-11-23 21:15:52

如果您不想使用 ASP.NET 生成主 JavaScript,则还有另外两个选项:

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

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

If you don't want to use ASP.NET to generate your main JavaScript, here are two other options:

  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 HttpHandler rather 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.

夜还是长夜 2024-11-23 21:15:52

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

假设您可以编写一个非常简单的 C# 类(或使用 Dictionary)来从 ASP.NET WebMethod 返回数据。结果看起来像这样:

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

我总是将 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);
        }
    });

然后,在页面上执行的 .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);
    }
}

Have you considered using $.ajax in 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.

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:

[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:

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:

// 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);
    }
}
秋心╮凉 2024-11-23 21:15:52

我知道已经晚了,但想分享我在这项任务中的经验)

我使用 AjaxMin。它可以在构建事件上将 resx 键值插入到 js 文件中。
这不是常见的方法,但它可以保留 html 而不需要不需要的脚本块,并且可以在缩小过程中完成(如果有的话)。

它的工作原理如下:

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

如果您有很多语言环境,您还需要对 ech 语言环境执行相同的操作。
在 js(以及 css)中编写资源键的语法如下:

Js 本地化

< a href="http://ajaxmin.codeplex.com/wikipage?title=CSSLocalization" rel="nofollow">CSS 本地化

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.

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:

Js localization

Css localization

别忘他 2024-11-23 21:15:52

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

我有一个独立的 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'
 }
});

然后,在这个 javascript 控件中:

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

每当我想显示资源时,我都会说(例如,显示一个警告说“完成”) :

alert(crmSettings.Resources.Done);

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

How about injecting it as part of a javascript control initialization? 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. When i initialize it, i pass an object containing all the resources i need inside javascript as follows:

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:

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文