I have a database object (a row), that has lots of properties (columns) that map to form fields (asp:textbox, asp:dropdownlist etc). I would like to transform this
The HtmlHelper class allows a conversion of Anonymouns Object to RouteValueDictonary and I suppose you could use a .ToString() on each value to get the string repersentation:
var linkAttributes = System.Web.Mvc.HtmlHelper.AnonymousObjectToHtmlAttributes(linkHtmlAttributes);
The down side is this is part of the ASP.NET MVC Framework. Using a .NET Reflector, the code inside of the method is as follows:
public static RouteValueDictionary AnonymousObjectToHtmlAttributes(object htmlAttributes)
{
RouteValueDictionary dictionary = new RouteValueDictionary();
if (htmlAttributes != null)
{
foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(htmlAttributes))
{
dictionary.Add(descriptor.Name.Replace('_', '-'), descriptor.GetValue(htmlAttributes));
}
}
return dictionary;
}
You'll see that this code is identical to the answer Yahia gave you, and his answer provides a Dictonary
EDIT - I've added the code for what could be a method to do your conversion:
EDIT 2 - I've added null checking to the code and used String.Format for the string value
public static Dictionary ObjectToDictionary(object value)
{
Dictionary dictionary = new Dictionary();
if (value != null)
{
foreach (System.ComponentModel.PropertyDescriptor descriptor in System.ComponentModel.TypeDescriptor.GetProperties(value))
{
if(descriptor != null && descriptor.Name != null)
{
object propValue = descriptor.GetValue(value);
if(propValue != null)
dictionary.Add(descriptor.Name,String.Format("{0}",propValue));
}
}
return dictionary;
}
And to go from a Dictionary to an object check http://automapper.org/ which was suggested in this thread Convert dictionary to anonymous object