How to correctly parse Dictionary<string, object> into

1.4k Views Asked by At

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);
    }
}
3

There are 3 best solutions below

2
On BEST ANSWER

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);
0
On

Comparer, Count, Keys, and Values are public properties of class Dictionary. So you are getting exactly what you are requesting. If you want actual key-value pairs, you need to iterate over Dictionary.

0
On

AnonymousObjectToHtmlAttributes method most probably uses reflection to iterate through public properties of the provided type. As seen in its documentation, the only properties besides the indexer are Comparer, Count, Keys and Values.