這是我如何做到這一點上的Visual Studio 2013:
- 對於全球資源,請右鍵單擊Project並選擇
Add > Add ASP.NET Folder > App_GlobalResources
。
對於本地資源,右鍵單擊您想要佔用資源的文件所在的文件夾,然後選擇Add > Add ASP.NET Folder > App_LocalResources
。
對於標籤和錯誤消息,我更喜歡使用LocalResources。這種做法使項目更有條理,易於修改。以下是link的更多詳細信息。
創建資源文件和名稱它們,如下所示:
![Creation](https://i.imgur.com/1ZtMbSy.png)
它可以創建多達App_LocalResources文件文件夾,因爲你需要,但再次重申,App_LocalResources文件文件夾,您將放置資源文件(.resx
)的位置必須與.aspx
,.Master
或位於同一文件夾中文件。
Frontend.Master.resx的標籤和消息對默認語言
Frontend.Master。 pt-br .resx for 巴西葡萄牙語標籤和消息。
如果用戶將其瀏覽器的語言更改爲pt-BR,則頁面使用pt-br.resx
。
創建資源項目。 名稱 =鍵,值 =顯示文本
![Editing](https://i.imgur.com/4cmAm5j.png)
使用本地或全局資源文件:
<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文件生成.designer.cs
文件。如果資源文件的名稱爲 'Labels.pt-br.resx',則該文件在名爲Resources
的全局namespace
中生成名爲'Labels'的靜態類 。負責這一點的是在資源文件屬性中定義的'自定義工具'GlobalResourceProxyGenerator
,您可以訪問編寫Resources.Labels.ResourceKey
的全局資源。
爲了LocalResources文件等作爲GlobalResources靜態訪問,你可以做到以下幾點:
- 選擇本地資源文件
- 按F4鍵或右鍵單擊並選擇「屬性」
- 在
Custom Tool
type'PublicResXFileCodeGenerator'
- On
Build Action
select Embedded Resource
- 此後重建您的應用程序或網站。現在您可以看到VisualStudio生成一個嵌套在資源文件中的
.designer.cs
文件。
如何使用它?
按照我在此答案中創建的結構,我們在MasterPages文件夾中有一個LocalResource,用於生成名稱空間WebFormsProject2.MasterPages.App_LocalResources
。 如果在另一個文本編輯器中打開'.designer.cs'(在本例中爲Frontend.Master.designer.cs
),您將看到它在名稱空間WebFormsProject2.MasterPages.App_LocalResources
上生成名爲Frontend_Master
的類以及一些與您創建的資源鍵名稱相同的靜態屬性在資源文件中。 現在您只需創建對此名稱空間的引用並訪問屬性,如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>
爲什麼我不能使用屬性內的資源,就像我在MVC中做的那樣? –