简体   繁体   中英

Mapping Data Annotation of a Model object to Custom Class object .net mvc

i'm wondering how to map A model object Into a more generic class object and saving values of DataAnnotation to specified field.

My Example Model that for example. I want to map 1 Model object to 1 FieldSetModel object, that contain the list of Model fields with value, and alla metadata provided by DataAnnotation.

  • 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

etc..

Model

    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 And i want to map values and DataAnnotationValues to This class related to the 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;
    }
}

As you have mentioned you can get attributes with the information from this question: 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();
}

Getting properties and their values is also quite simple using reflection. You can refer to this question: 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));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM