DisplayFor
doesn't work like the other *For
helpers. Like EditorFor
, it's what's referred to as a "templated helper". In other words, what it renders is controlled by a template that can be modified. Importantly, for both of these methods, if you look up their documentation in MSDN, you'll see that the parameter that would normal correspond to htmlAttributes
with the other helpers, instead refers to additionalViewData
with these two. This is because, again, their output is controlled by essentially views, which take ViewData
.
Additionally, with DisplayFor
in particular, the default templates pretty much just output the value, with no HTML. If you pass a string property, for example, the output will be the value of that string and nothing else. Therefore, there's nothing to tie the HTML attributes to, even if you could pass them in.
If you want to do what you're trying to do, you'd have to create custom display templates. This can be done by adding views named after types (e.g. String
, Boolean
, Byte
etc.) or members of the DataType
enum (CreditCard
, EmailAddress
etc.), to Views\Shared\DisplayTemplates
. For example, if you created a view at Views\Shared\DisplayTemplates\String.cshtml
, then when you called DisplayFor
with a property of type string
, that view would be utilized to render it. You could then wrap the value that would otherwise be just output directly in some HTML of your choice and utilize ViewData
to apply the appropriate HTML attributes. For example:
<span class="@ViewData["class"]">@ViewData.TemplateInfo.FormattedModelValue</span>