国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術文章
文章詳情頁

ASP.NET MVC實現本地化和全球化

瀏覽:196日期: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
相關文章:
主站蜘蛛池模板: 增城市| 田林县| 安宁市| 西峡县| 连城县| 金华市| 谷城县| 建瓯市| 宾阳县| 六安市| 梁平县| 新晃| 仙居县| 台东县| 林州市| 兴文县| 泊头市| 九台市| 专栏| 河间市| 巴彦淖尔市| 徐汇区| 德清县| 盱眙县| 阿尔山市| 九龙坡区| 浦县| 鸡东县| 延庆县| 南郑县| 常宁市| 安泽县| 富锦市| 神农架林区| 隆安县| 北流市| 共和县| 宁国市| 福鼎市| 永吉县| 印江|