我正在尝试翻译我的 aspx 页面中按钮的文本。我正在使用 asp.net webforms 但我还没有实现它。在 MVC 中,我可以做我想做的事,但在网络表单中,这让我很痛苦。
这是我的资源
我试图在 aspx 中使用它但没有成功。我可以用这段代码在代码后面完成
protected void Page_Load(object sender, EventArgs e)
{
Button1.Text = Properties.Resources.BUTTON_SEND;
}
但是我真的很想直接在页面中做
<asp:Button ID="Button1" runat="server" Text="HERE_COMES_THE_LOCALIZABLE_TEXT" />
有人可以帮帮我吗?
最佳答案
这就是我在 Visual Studio 2013、2015 和 2017 上的做法:
- 对于全局资源,右键单击项目并选择
添加 > 添加 ASP.NET 文件夹 > App_GlobalResources
。 对于本地资源,右键单击要使用资源的文件所在的文件夹,然后选择
添加 > 添加 ASP.NET 文件夹 > App_LocalResources
。For labels and error messages I prefer to use LocalResources. This practice makes the project more organized and easy to modify. Here's a link for more details.
创建资源文件并命名如下:
It's possible to create as many App_LocalResources folders as you need, but again, the App_LocalResources folder, where you will place the resource files (
.resx
), must be in the same folder as the.aspx
,.Master
or.ascx
file.Frontend.Master.resx 用于使用默认语言的标签和消息
Frontend.Master.pt-br.resx 用于巴西葡萄牙语标签和消息。If user change the language of it browser to pt-BR then the page use the
pt-br.resx
.创建资源项。 名称 = 键,值 = 显示文本
使用本地或全局资源文件:
<head> <title><%= GetGlobalResourceObject("Labels", "HelloWorld") %></title> </head> <body> <button type="button"> <span><%= GetLocalResourceObject("Header_NavButton_Sr") %></span> <asp:Literal runat="server" Text="<%$ resources:Header_NavButton_Sr %>"></asp:Literal> </button> <a href="index.html"><%= GetLocalResourceObject("Header_TextLogo") %></a> <asp:TextBox ID="tb1" runat="server" Text="<%$ resources:Navbar_Home %>"></asp:TextBox> </body>
GlobalResources files generate a
.designer.cs
file. This file generate a static class named 'Labels', if the name of resource file is 'Labels.pt-br.resx', in a globalnamespace
calledResources
. The responsible for this is the 'Custom Tool'GlobalResourceProxyGenerator
that is defined in resource file properties, and you can access global resources writingResources.Labels.ResourceKey
.
要使 LocalResources 文件像 GlobalResources 一样静态访问,您可以执行以下操作:
- 选择本地资源文件
- 按 F4 或右键单击并选择“属性”
- 在
自定义工具
上输入“PublicResXFileCodeGenerator” - 在
Build Action
上选择Embedded Resource
- 在此之后,重建您的应用程序或网站。现在您可以看到 VisualStudio 生成了一个嵌套在资源文件中的
.designer.cs
文件。
如何使用?
按照我在此答案中创建的结构,MasterPages 文件夹中有一个 LocalResource 生成 namespace WebFormsProject2.MasterPages.App_LocalResources
。
如果您在另一个文本编辑器上打开“.designer.cs”,在本例中为 Frontend.Master.designer.cs
,您将看到它生成一个名为 Frontend_Master
在命名空间 WebFormsProject2.MasterPages.App_LocalResources
和一些与您在资源文件中创建的资源键同名的静态属性。
现在您只需创建对此命名空间的引用并访问属性,如 Frontend_Master.Header_TextLogo
。
例子:
<%@ Import Namespace="WebFormsProject2.MasterPages.App_LocalResources" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title><%= Frontend_Master.Header_TextLogo %></title>
</head>
<body>...</body>
关于c# - 在 aspx 页面中使用 Asp.Net WebForms 上的属性资源本地化文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42366100/