ASP.NET MVC實現(xiàn)本地化和全球化
在開發(fā)多語言網(wǎng)站時,我們可以為某種語言創(chuàng)建一個資源文件,根據(jù)瀏覽器所設(shè)置的不同語言偏好,讓運行時選擇具體使用哪個資源文件。資源文件在生成程序集的時候被嵌入到程序集。
本篇體驗,在ASP.NET MVC中實現(xiàn)全球化和本地化,比如,當瀏覽器選擇英文,就讓某些頁面元素顯示英文;當瀏覽器選擇用中文瀏覽,則顯示中文。
使用Visual Studio 2013創(chuàng)建一個無身份驗證的MVC項目。
創(chuàng)建如下的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方法中添加一個有關(guān)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="創(chuàng)建" /> </div></div>
現(xiàn)在,我們希望,當瀏覽器選擇英語的時候,頁面元素都顯示英文。
在解決方案下創(chuàng)建一個名稱為MyResources的類庫。
創(chuàng)建有關(guān)中文的資源文件,并把訪問修飾符設(shè)置為public:
創(chuàng)建有關(guān)英文的資源文件,也把訪問修飾符設(shè)置為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項目,出現(xiàn)報錯。
修改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中設(shè)置如下:
<system.web> ...... <globalization culture="auto" uiCulture="auto" enableClientBasedCulture="true"></globalization> </system.web>
在chrome瀏覽器語言設(shè)置中選擇英語。
刷新后,效果如下:
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習或者工作具有一定的參考學(xué)習價值,謝謝大家對的支持。如果你想了解更多相關(guān)內(nèi)容請查看下面相關(guān)鏈接
相關(guān)文章:
1. ASP.NET MVC使用正則表達式驗證手機號碼2. ASP.NET MVC把數(shù)據(jù)庫中枚舉項的數(shù)字轉(zhuǎn)換成文字3. ASP.NET MVC通過勾選checkbox更改select的內(nèi)容4. ASP.NET MVC使用Quartz.NET執(zhí)行定時任務(wù)5. ASP.NET MVC使用異步Action的方法6. ASP.NET MVC使用jQuery的Load方法加載靜態(tài)頁面及注意事項7. ASP.NET MVC實現(xiàn)城市或車型三級聯(lián)動8. ASP.NET MVC實現(xiàn)橫向展示購物車9. ASP.NET MVC實現(xiàn)區(qū)域或城市選擇10. ASP.NET MVC實現(xiàn)單個圖片上傳、限制圖片格式與大小并在服務(wù)端裁剪圖片
