MVC - Convert an IDictionary or RouteValueDictionary to object htmlAttributes

.net, asp.net-mvc, c#

Solution

To answer your question anyway:

    public static object ToAnonymousObject(this IDictionary<string, object> @this)
    {
        var expandoObject = new ExpandoObject();
        var expandoDictionary = (IDictionary<string, object>) expandoObject;

        foreach (var keyValuePair in @this)
        {
            expandoDictionary.Add(keyValuePair);
        }
        return expandoObject;
    }

Problem

I've created a HTML Helper Extension which calls a Editor Template Partial View (MyView) in MVC. I'm passing additional HTML attributes to the HTML Helper Extension via the object htmlAttributes parameter. In the HTML Helper Extension the The htmlAttributes are converted to an RouteValueCollection (could use IDictionary here) and stored in the ModelProperty object: ``` public static MvcHtmlString TextBoxFor(this HtmlHelper html, ModelProperty prop, object htmlAttributes) { prop.ControlHtmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes); return PartialExtensions.Partial(html, "MyView", prop); } ``` In the 'MyView' Partial View I want to render the control and with the passed HTML attributes so I call: ``` Html.TextArea(Model.ControlName, Model.Value, Model.ControlHtmlAttributes); ``` Howvever this dosnt work because the 3rd parameter should be 'object htmlAttributes' how to I convert the Model.ControlHtmlAttributes to object htmlAttibutes?

Original source