c# - Get value from property in foreach loop -
i having issue getting values property of type viewmodel passing in. current method, believe name of property being stored right, can't seem value work. advice appreciated. believe have problems dictionary when type of value not string also, problem later :).
here method taking in viewmodel type:
public type convertmodel(type mytype) { dictionary<string,string> dic = new dictionary<string,string>(); foreach (var prop in mytype.getproperties()) { dic.add(prop.name, prop.getvalue(mytype,null).tostring()); } //return mytype; }
this how method being called(ignore method name trying idea out):
public actionresult index() { var viewmodel = new myviewmodel() { firstname = "shawn", lastname = "michaels" }; var newtype = convertmodel(viewmodel.gettype()); return view(); }
the sample output pass model related viewmodel (say userviewmodel , usermodel, usermodel filled userviewmodel properties , values, except method should tank in 2 related models above.)
cause property can null, raise error can 1 of these options:
updateing
just make sure pass instance of object instead of type:
instead of public type convertmodel(type mytype) {
use below code
public t convertmodel<t>(t obj) { var dic = new dictionary<string,object>(); foreach (var prop in obj.gettype().getproperties()) { dic.add(prop.name, prop.getvalue(obj,null)); }
first: create dictionary obejct
var dic = new dictionary<string,object>(); foreach (var prop in obj.gettype().getproperties()) { dic.add(prop.name, prop.getvalue(obj,null)); }
second: can cast string , if can not cast put null in dictionary
foreach (var prop in obj.gettype().getproperties()) { dic.add(prop.name, (string)prop.getvalue(obj,null)); }
or
foreach (var prop in mytype.getproperties()) { dic.add(prop.name, convert.tostring(prop.getvalue(mytype,null))); }