Search code examples
c#asp.net-mvcdictionaryanonymous-objects

How to correctly parse Dictionary<string, object> into


I was working on HtmlHelper.AnonymousObjectToHtmlAttributes.

It works well with anonymous object:

var test = new {@class = "aaa", placeholder = "bbb"};
var parseTest= HtmlHelper.AnonymousObjectToHtmlAttributes(test);

The result parseTest has two key-value pairs.

But for Dictionary object:

var attrsInDict = new Dictionary<string,object>() {            
    {"class", "form-control"},
    {"placeholder", "Select one..."}
};
var attrs = HtmlHelper.AnonymousObjectToHtmlAttributes(attrsInDict );

The attrs obtained is a strange object, with 4 Keys and 4 Values. The 4 keys are Comparer, Count, Keys,Values.

Some other SO post asking about the difference between the two(here). The selected answer says

There's not too much difference...

Really? And what is the correct way to parse the attrsInDict and get the same result as the one we get from an anonymous object?

For, I intend to merge attribues in the following code:

var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
foreach (var item in attrs)
{
    if (attr.ContainsKey(item.Key))
    {
        attr[item.Key] = $"{attr[item.Key]} {item.Value}";
    }
    else
    {
        attr.Add(item.Key, item.Value);
    }
}

Solution

  • The results are not strange -- they are exactly what I would expect from a method called AnonymousObjectToHtmlAttributes. The method expects input like test, an actual anonymous object, not an instance of concrete class like Dictionary.

    What you're seeing in the case of passing an instance of Dictionary are its public properties, which are indeed the Comparer, Count, Keys, and Values properties.

    The return type of AnonymousObjectToHtmlAttributes is RouteValueDictionary. That class has a constructor overload that accepts a IDictionary<string, object>.

    To correctly use your dictionary, do this:

    var attrs = new RouteValueDictionary(attrsInDict);