将Model对象的数据注释映射到Custom Class对象.net mvc

时间:2014-11-19 09:18:30

标签: c# asp.net-mvc mapping data-annotations automapping

我想知道如何将模型对象映射到更通用的类对象并将DataAnnotation的值保存到指定的字段。

我的示例模型,例如。我想将1个Model对象映射到1个FieldSetModel对象,其中包含带有值的Model字段列表,以及DataAnnotation提供的alla元数据。

  • Model.Name - > FieldSet.FormModel [1] .ID
  • Model.Name - > FieldSet.FormModel [1] .name
  • Model。(DataAnnotation(MaxLenght) - > FieldSet.FormModel [1] .MaxLenght
  • Model。(DataAnnotation(Display) - > FieldSet.FormModel [1] .DisplayName

等。

模型

    public virtual Int32 Id { get; protected set; }
    #region Login
    [Required,MaxLength(30)]
    [Display(Name = "Nome Utente")]
    public virtual string UserName { get; set; }

    [Required, MaxLength(200),DataType(DataType.EmailAddress)]
    [Display(Name = "Email")]
    public virtual string Email { get; set; }

    [Required]
    [Display(Name = "Password"),DataType(DataType.Password),MinLength(6)]
    [StringLength(100, ErrorMessage="La lunghezza di {0} deve essere di almeno {2} caratteri.", MinimumLength=6)]
    public virtual string Password { get; set; }
    #endregion

FieldSetModel 我想将值和DataAnnotationValues映射到与View相关的此类:

   public class FieldSetModel
{
    public string Title;
    public List<Field> FormModel = new List<Field>();

}

public class Field{
    public string Id            { get; private set; }
    public string Name          { get; private set; }
    public string DisplayName;
    public string DataType = "text";
    public int MaxLenght = 100;
    public int MinLenght = 0;
    public string FormatErrorMessage =  "Formato non valido";
    public string RangeErrorMessage =   "Range non valido";
    public string RequiredErrorMessage = "Valore  Non Corretto";
    public string Pattern;
    public string DisplayFormat;

    public string Value;
    public bool Error;

    public Field(string name)
    {
        this.Name = name;
        this.Id = name;
    }
}

1 个答案:

答案 0 :(得分:0)

正如您所提到的,您可以使用此问题中的信息获取属性:How to retrieve Data Annotations from code? (programmatically)

public static T GetAttributeFrom<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();
}

使用反射获取属性及其值也非常简单。您可以参考以下问题:How to get the list of properties of a class?

class Foo {
    public int A {get;set;}
    public string B {get;set;}
}
...
Foo foo = new Foo {A = 1, B = "abc"};
foreach(var prop in foo.GetType().GetProperties(BindingFlags.Public)) {
    Console.WriteLine("{0}={1}", prop.Name, prop.GetValue(foo, null));
}