c# - Mapping Data Annotation of a Model object to Custom Class object .net mvc -
i'm wondering how map model object more generic class object , saving values of dataannotation specified field.
my example model example. want map 1 model object 1 fieldsetmodel object, contain list of model fields value, , alla metadata provided 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 , want map values , dataannotationvalues class related 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 have mentioned can attributes information question: how retrieve data annotations code? (programmatically)
public static t getattributefrom<t>(this object instance, string propertyname) t : attribute { var attrtype = typeof(t); var property = instance.gettype().getproperty(propertyname); return (t)property .getcustomattributes(attrtype, false).first(); }
getting properties , values quite simple using reflection. can refer question: how list of properties of class?
class foo { public int {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)); }
Comments
Post a Comment