文章詳情頁
ASP.NET MVC實現本地化和全球化
瀏覽:184日期:2022-06-09 11:30:35
在開發多語言網站時,我們可以為某種語言創建一個資源文件,根據瀏覽器所設置的不同語言偏好,讓運行時選擇具體使用哪個資源文件。資源文件在生成程序集的時候被嵌入到程序集。
本篇體驗,在ASP.NET MVC中實現全球化和本地化,比如,當瀏覽器選擇英文,就讓某些頁面元素顯示英文;當瀏覽器選擇用中文瀏覽,則顯示中文。
使用Visual Studio 2013創建一個無身份驗證的MVC項目。
創建如下的Model:
public class Student {public int Id { get; set; }[Display(Name="姓名")][Required(ErrorMessage="必填")]public string Name { get; set; }[Display(Name = "年齡")][Required(ErrorMessage = "必填")]public int Age { get; set; } }
生成解決方案。
在HomeController中Index方法中添加一個有關Student的強類型視圖,并選擇默認的Create模版。大致如下:
@model GlobalAndLocal.Models.Student<h2>Index</h2><div> @Html.LabelFor(model => model.Name, new { @class = "control-label col-md-2" }) <div>@Html.EditorFor(model => model.Name)@Html.ValidationMessageFor(model => model.Name) </div></div><div> <div><input type="submit" value="創建" /> </div></div>
現在,我們希望,當瀏覽器選擇英語的時候,頁面元素都顯示英文。
在解決方案下創建一個名稱為MyResources的類庫。
創建有關中文的資源文件,并把訪問修飾符設置為public:
創建有關英文的資源文件,也把訪問修飾符設置為public:
生成類庫。
在MVC項目中引用該類庫。
修改Student類如下:
public class Student {public int Id { get; set; }[Display(Name=MyResources.Resource.Name)][Required(ErrorMessage=MyResources.Resource.NameRequiredError)]public string Name { get; set; }[Display(Name = MyResources.Resource.Age)][Required(ErrorMessage = MyResources.Resource.AgeRequiredError)]public int Age { get; set; } }
在Index強類型視圖頁中,修改如下:
<h2>@MyResources.Resource.IndexHeader</h2><div> @Html.LabelFor(model => model.Name, new { @class = "control-label col-md-2" }) <div>@Html.EditorFor(model => model.Name)@Html.ValidationMessageFor(model => model.Name) </div></div><div> <div> <input type="submit" value="@MyResources.Resource.Submit" /> </div></div>
運行MVC項目,出現報錯。
修改Student類如下:
public class Student {public int Id { get; set; }[Display(Name="Name", ResourceType=typeof(MyResources.Resource))][Required(ErrorMessageResourceName = "NameRequiredError", ErrorMessageResourceType = typeof(MyResources.Resource))]public string Name { get; set; }[Display(Name = "Age", ResourceType = typeof(MyResources.Resource))][Required(ErrorMessageResourceName = "AgeRequiredError", ErrorMessageResourceType = typeof(MyResources.Resource))]public int Age { get; set; } }
最后,還需要在Web.config中設置如下:
<system.web> ...... <globalization culture="auto" uiCulture="auto" enableClientBasedCulture="true"></globalization> </system.web>
在chrome瀏覽器語言設置中選擇英語。
刷新后,效果如下:
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對的支持。如果你想了解更多相關內容請查看下面相關鏈接
標簽:
ASP.NET
相關文章:
1. ASP.NET MVC使用異步Action的方法2. ASP.NET MVC使用Boostrap實現產品展示、查詢、排序、分頁3. ASP.NET MVC獲取多級類別組合下的產品4. ASP.NET MVC實現登錄后跳轉到原界面5. ASP.NET MVC使用Identity增刪改查用戶6. ASP.NET MVC通過勾選checkbox更改select的內容7. 使用EF Code First搭建簡易ASP.NET MVC網站并允許數據庫遷移8. log4net在Asp.net MVC4中的使用過程9. ASP.NET MVC實現區域或城市選擇10. ASP.NET MVC使用JSAjaxFileUploader插件實現單文件上傳
排行榜