在asp mvc中为模型使用特定于语言的资源

时间:2014-08-07 08:30:05

标签: asp.net-mvc asp.net-mvc-4

我感兴趣的是如何使用预定义的模型在视图中显示基于语言的通知。

例如,这是我模型的一部分:

public class PrivateModel
    {
        [Required(ErrorMessage = "Please fill in your last name.")]
        [Display(Name = "First Name")]
        public string FirstName { get; set; }

        [Required(ErrorMessage = "Please fill in your last name.")]
        [Display(Name = "Last Name")]
        public string LastName { get; set; }

    }

以下是观点:

@using(Html.BeginForm())
{
    <div>
        @Html.LabelFor(m => m.FirstName)
        @Html.TextBoxFor(m=>m.FirstName)
        @Html.ValidationMessageFor(m => m.FirstName)

    </div>
    <div>
        @Html.LabelFor(m => m.LastName)
        @Html.TextBoxFor(m=>m.LastName)
        @Html.ValidationMessageFor(m => m.LastName)
    </div>
    <div>
        <input type="submit" value="First click"
    </div>

如果我想让First Name有不同语言的错误消息,我该怎么办?

是否可以用语言资源的ID替换实际值,并使用以下内容:

[Required(ErrorMessage = "100")]//Please enter your first name
            [Display(Name = "101")]// First name
            public string FirstName { get; set; }

然后代替

 @Html.ValidationMessageFor(m => m.FirstName)

使用

@Html.ValidationMessageFor(m => GetSource(m.FirstName, culture))

2 个答案:

答案 0 :(得分:1)

您可以使用:

ErrorMessageResourceName 

数据注释属性。

然后,您可以将所有消息存储在本地化资源文件中,然后密钥将根据所选本地化查找字符串。

全球化是一个很大的话题,但这应该让你开始。

答案 1 :(得分:0)

请参阅以下本地化完整指南链接

http://adamyan.blogspot.co.uk/2010/02/aspnet-mvc-2-localization-complete.html

http://www.asp.net/mvc/overview/internationalization

public class LocalizedDisplayNameAttribute : DisplayNameAttribute
{
  private PropertyInfo _nameProperty;
  private Type _resourceType; //Declare Cache object here to select property name

  public LocalizedDisplayNameAttribute(string displayNameKey)
      : base(displayNameKey)
  {

  }

  public Type NameResourceType
  {
      get
      {
          return _resourceType;
      }
      set
      {
          _resourceType = value;
          //initialize nameProperty when type property is provided by setter
      // _nameProperty = _resourceType.GetProperty(base.DisplayName, BindingFlags.Static | BindingFlags.Public);
          _nameProperty = select property from Cache values for Database 
      }
  }

  public override string DisplayName
  {
     get
     {
          //check if nameProperty is null and return original display name value
          if (_nameProperty == null)
          {
              return base.DisplayName;
          }

          return (string)_nameProperty.GetValue(_nameProperty.DeclaringType, null);
      }
   }