For example if you check these two extension methods the only difference is type of htmlAttributes so you can pass your htmlAttributes in two different ways:
public static MvcHtmlString TextBoxFor<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression,
IDictionary<string, object> htmlAttributes);
public static MvcHtmlString TextBoxFor<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression,
object htmlAttributes);
And use them in either of these ways:
@Html.TextBoxFor(model => model.TagLine,
new { @placeholder = "We live to make art." })
@Html.TextBoxFor(model => model.TagLine,
new Dictionary<string, object> {
{ "placeholder", "We live to make art." } })
I have checked MVC source code and I know in the background they use same method, but the one which accepts the anonymous object uses HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes) to make the anonymous object a dictionary.
In my point of view, views are cleaner to use anonymous object. What do you think guys? Are there any drawbacks to using an anonymous object?
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.