Friday, 17 June 2016

Fill dictionary with Table (model) column name and its value - with reflection

No comments
//Dictionary

 public Dictionary<string, string> BindModelDictioanry<T>(T t) where T : class
        {
            Dictionary<string, string> dictModel = new Dictionary<string, string>();
            foreach (PropertyInfo info in t.GetType().GetProperties())
            {
                PropertyInfo propertyInfos = t.GetType().GetProperty(info.Name);
                if (propertyInfos.PropertyType == typeof(ListItemValue))
                {
                    var value = (your column datatype)info.GetValue(t, null);
                    var key = info.Name; //This will be column name
                    dictModel.Add(key, value.ToString()); //This will be column value
                }          
            }
            return dictModel;

        }

//Using reflection

ViewModel model = new ViewModel();
model.DicFormaData = BindModelDictioanry<PersonalDetails>(personalDetailsData);

//model.DicFormaData 

public Dictionary<string, string> DicFormaData { get; set; }