无法覆盖数据属性

时间:2015-06-15 11:39:45

标签: asp.net asp.net-mvc

首先,Hee是简单数据属性的样子

[Required(ErrorMessage="843")]

问题是我需要从数据库中获取数据注释属性的错误消息(取决于我拥有的数字 - 在本例中为843)。所以我在我的代码中尝试的是我得到它的类型的每个属性的属性。然后,对于此属性的每个属性,我在扩展方法的帮助下得到它的错误消息。问题是我无法覆盖属性的errormessage属性。

     [HttpPost]
  public virtual ActionResult Register(Users user)
  { 
       if (ModelState.IsValid)
      {
        //code when everything ids OK
      }
      foreach (var prop in typeof(Users).GetProperties())
      {
                    object[] attrs = prop.GetCustomAttributes(false);
                    if (attrs == null || attrs.Length == 0)
                        continue;  
                    foreach (var attr in attrs)
                    {
                        string errorMes = user.GetAttribute<RequiredAttribute>(prop.Name).ErrorMessage;                       
                        user.GetAttribute<RequiredAttribute>(prop.Name).ErrorMessage = repository.GetAttribute(errorMes );
                    }
     }

这是我的扩展方法,它获取了实例的确切属性:

public static T GetAttribute<T>(this object instance, string propertyName) where T : Attribute
        {
            var attrType = typeof(T);
            var property = instance.GetType().GetProperty(propertyName);
            return (T)property.GetCustomAttributes(attrType, false).First();
        }     

无论我给出的是什么数字,我总是有默认的错误消息=而奇怪的是我清楚地看到属性类的errormessage属性可以设置。 你能给出简单的线索或其他方法,以便实现我的目标

0 个答案:

没有答案