Am new to MVC, am am trying to apply CSS styles to Html.DisplayFor helper inside my template file: Shared>>EditorTemplate>>Contacts.cshtml. Below is my code:
@model People.Contacts
<div>
@Html.DisplayNameFor(m => m.Name) <span class="myclass">@Html.DisplayFor(m => m.FirstName) @Html.DisplayFor(m => m.LastName)</span></div>
and my css class outside this template looks like this:
.myclass{font:italic bold;}
Html.DisplayFor
does not support passing HTML attributes, including class/style. At it's most basic it merely renders the value, without any HTML, and with editor/display templates, it just renders whatever's in the template.
First, if you have EditorTemplates\Contacts.cshtml
, that will actually never be used by DisplayFor
. For DisplayFor
you need a separate template in Views\Shared\DisplayTemplates
. As its name implies EditorTemplates
is used by EditorFor
.
Either DisplayFor
or EditorFor
are basically the same as calling Html.Partial
. There's just some additional logic to deal with a specific model property and look by default in DisplayTemplates
/EditorTemplates
for the view. That said, you can pass additional data to them the same as you would with a partial, via ViewData
.
For example, if you were to call @Html.DisplayFor(m => m.FirstName, new { @class = "myclass" })
, then nothing would happen by default, but you would have a value of "myclass"
in ViewData["class"]
. You could then use that to modify a part of your template. For example:
Views\Shared\DisplayTemplates\Contacts.cshtml
<span @(ViewData["class"] != null ? "class='" + ViewData["class"] + "'" : string.Empty)>
@ViewData.TemplateInfo.FormattedModelValue
</span>
That checks to see if ViewData["class"]
has a value, and if so, adds a class attribute with that value to the span.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With