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)
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?