ASP.NET MVC实现本地化和全球化

这篇文章介绍了ASP.NET MVC实现本地化和全球化的方法,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

在开发多语言网站时,我们可以为某种语言创建一个资源文件,根据浏览器所设置的不同语言偏好,让运行时选择具体使用哪个资源文件。资源文件在生成程序集的时候被嵌入到程序集。

本篇体验,在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 

Index

@Html.LabelFor(model => model.Name, new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.Name) @Html.ValidationMessageFor(model => model.Name)

现在,我们希望,当浏览器选择英语的时候,页面元素都显示英文。

在解决方案下创建一个名称为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强类型视图页中,修改如下:

@MyResources.Resource.IndexHeader

@Html.LabelFor(model => model.Name, new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.Name) @Html.ValidationMessageFor(model => model.Name)

运行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中设置如下:

   ...... 

在chrome浏览器语言设置中选择英语。

刷新后,效果如下:

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对0133技术站的支持。如果你想了解更多相关内容请查看下面相关链接

以上就是ASP.NET MVC实现本地化和全球化的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » ASP编程