Difference between anonymous class and IDictionary<string,object> for htmlAttributes in ASP.NET MVC?

不羁岁月 提交于 2019-11-30 21:41:53

There's not too much difference, however using the anonymous object is a cleaner and more readable syntax for the caller, and now considered more standard practice. There might be a slight, negligible performance benefit to using IDictionary if you're a fan of micro-optimisation.

The IDictionary overload option has probably stuck since ASP.NET MVC 1.0 CTP days when C# 3.0 and anonymous objects were still quite new. Eilon Lipton's blog post proposing Using C# 3.0 Anonymous Types as Dictionaries gives some background.

The IDictionary<string, object> is there for a special reason. If you want to adjust the htmlAttributes parameter in a extended function then this is possible. I have several extensions of the Html.TextBox function. I have for example a function thats called: TextBoxOrDisplayForNoDiaCritics. This function enables a TextBox or displays a disabled textbox. Additional it also removes DiaCritics from the textbox. I do this with a Javascript function. The event onchange fires on the input tag. So in this function I add that onchange event with the javascript function name to the htmlAttributes list. If I use a IDictionary thats easy but when I use an object that will be much harder.

So when you start your project its important to recognize what purpose your Html Helpers have to serve. In my case because I recognize the importance in my project I use IDictionary everywhere in my Project.

Van Thoai Nguyen

Chris answers all the thing.

I give 1 more reason why use IDictionary: Prior to MVC 3.0, you could not use anonymous object when you need a HTML5 attribute like "data-something" :D

Cheers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!