久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

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

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

瀏覽:244日期: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
相關文章:
主站蜘蛛池模板: 巴林左旗| 定西市| 潜山县| 佳木斯市| 江津市| 雅江县| 东兰县| 石棉县| 孝昌县| 孟津县| 盘山县| 肃北| 垦利县| 山东| 仁化县| 崇文区| 渝北区| 吐鲁番市| 郯城县| 宝鸡市| 朝阳区| 两当县| 彭阳县| 松江区| 彭泽县| 平南县| 三穗县| 周至县| 花垣县| 永川市| 繁昌县| 从化市| 靖江市| 海城市| 保定市| 离岛区| 驻马店市| 溧水县| 永平县| 内乡县| 阿克苏市|