Home
> Programming > IDictionary from anonymous type
IDictionary from anonymous type
In ASP.NET MVC, we can specify what attributes appear on our HTML elements by passing an anonymous type as an argument.
@Html.TextBox("my-textbox", "hello world", new { @class = "css-class", custom = "custom" })
In this example, we’re specifying that the input
element will have a class
attribute and a custom
attribute when rendered.
Inspired by this, I needed a way to convert an anonymous type to an IDictionary<string, object>
. I created this extension method that allows an object to be converted to a dictionary.
public static class ExtensionMethods { public static IDictionary<string, object> ToDictionary(this object data) { BindingFlags publicAttributes = BindingFlags.Public | BindingFlags.Instance; Dictionary<string, object> dictionary = new Dictionary<string, object>(); foreach (PropertyInfo property in data.GetType().GetProperties(publicAttributes)) { if (property.CanRead) dictionary.Add(property.Name, property.GetValue(data, null)); } return dictionary; } }
This extends the object
type and adds a ToDictionary
extension method.
var anonymous = new { First = "John", Last = "Doe" }; IDictionary<string, object> dictionary = anonymous.ToDictionary();
Alternately, if we’re working in an ASP.NET MVC project, we can use RouteValueDictionary
to convert an anonymous type to a dictionary.
var anonymous = new { First = "John", Last = "Doe" }; RouteValueDictionary dictionary = new RouteValueDictionary(anonymous); string firstName = dictionary["First"].ToString(); string lastName = dictionary["Last"].ToString();
Thanks – that just saved me 20 minutes with the compiler
Awesome. Found just what I was looking for!
Not to rain on your parade too much this is available directly from .NET
HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes)
What’s really cool is when you use this in combination with the TagBuilder class
var tagBuilder = new TagBuilder(“input”);
tagBuilder.MergeAttribute(“type”, “hidden”);
tagBuilder.MergeAttribute(“name”, inputName);
tagBuilder.GenerateId(inputName);
if (value != null)
tagBuilder.MergeAttribute(“value”, value.ToString());
if (htmlAttributes != null) tagBuilder.MergeAttributes(HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes), replaceExisting: true);
Thank you dotnetchris, I did not know about that method.
But my original intent was to create an extension method for non-ASP.NET projects, such as window services or console applications. For those cases, I may not want to reference the System.Web.Mvc assembly in order to use the HtmlHelper. For example, I may be deploying a service to an environment where ASP.NET MVC is not installed, since it’s not part of the default .NET installation. There may also be other cases where my projects have not been upgraded to .NET 4.0 yet.
The MVC dependency is a semi-valid concern, however with VS2010 SP1 it’s easily overcome. You can use “deployable dependencies” that basically just puts the MVC dll in your bin directory when you publish.
On the pragmatist side I can understand not wanting a web dependency in an executable.
I’m not 100% sure which MVC this was added in whether it’s from 2 or 3, so it might only require a dependency on .NET3.5.
Of course with this being said I feel bad for any company that has such a bad handle on their technology usage that they can’t forward migrate to .NET4 because there’s really almost no justifiable reason to not be using 4.
There is a valid reason for a business not to upgrade, in fact there are 2. Time & money. If you have a test and building environment based on the 2/3.5 framework it takes time to upgrade all of these. It’s difficult trying to justify this time and money to any non-technical person espeically when the benefits aren’t immediately tangible.
Any business that hamstrings their software developers with legacy technology is asking for failure. You can’t expect success when you make erroneous decisions to justify any reason for not using the latest version of .NET.
Hello blogger, i must say you have high quality content here.
Your page should go viral. You need initial traffic only.
How to get it? Search for; Mertiso’s tips go viral