【问题标题】:Overriding validation attribute from a base Model覆盖基础模型的验证属性
【发布时间】:2012-02-14 13:38:35
【问题描述】:

我有一个名为 MyController 的 MVC 控制器和一个名为 MyAction 的操作。另一方面,我有一个名为 MyModel 的模型,所有这些类都在一个名为 Portal.Website(Asp.net MVC3 应用程序)的项目中,我将其用作通用网站并存储我将添加的自定义网站的通用功能未来。

另一方面,我有另一个引用 Portal.Website 项目的网站项目,名为 Portal.Website.MyCustomWebsite。

这是通用网站部分中的视图模型 MyModel.cs:

namespace Portal.Website
{
    public class MyModel
    {
        [Required(ErrorMessage="The field Name is required.")]
        [Display("MyPropertyOriginal")]
        public virtual string Name{get;set;}
    }
}

这是通用网站部分中的控制器和操作:

namespace Portal.Website
{
    public class MyController: Controller
    {
       [HttpPost]
       public ActionResult MyAction(MyModel model)
       {
          if(Model.IsValid)
          ....
          //My issue: Im getting the error message in english, not the overridden one.

       }
    }
}

这是我在自定义部分创建的视图模型:

namespace Portal.Website.MyCustomWebsite
{
    public class MyModel: MyModel
    {
        [Required(ErrorMessage="My error message in other language.")]
        [Display("MyPropertyOverriden")]
        public override string Name{get;set;}
    }
}

我的问题:

我想覆盖Required 属性的ErrorMessage。出于这个原因,我在我的自定义项目中创建了一个新模型。另一方面,我想使用已经在我的公共部分中定义的控制器/动作(MyController/MyAction)。

你知道这是否可能吗?我只遇到了Required 属性的问题,但Display 属性的问题很完美。

提前致谢。 问候。 何塞。

【问题讨论】:

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


    【解决方案1】:

    您可能想查看这篇文章,其中提出了两种可能的解决方案:

    http://www.codeproject.com/Articles/130586/Simplified-localization-for-DataAnnotations

    我发现使用我的自定义逻辑重新创建一些 DataAnnotation 类更有意义。

    【讨论】:

      【解决方案2】:

      MVC3 比它的前辈对 I18N(国际化)提供了更好的支持 - 您可以传递 RequiredAttribute 资源类的类型和资源键,错误消息将以最合适的语言显示:

      [Required(ErrorMessageResourceType = typeof(MyResources), ErrorMessageResourceName = "ResourceKey")]
      public override string Name { get; set; }
      

      【讨论】:

        猜你喜欢
        • 2019-06-22
        • 1970-01-01
        • 2015-01-12
        • 1970-01-01
        • 1970-01-01
        • 2014-10-06
        • 2018-12-01
        • 2014-03-23
        • 1970-01-01
        相关资源
        最近更新 更多