Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applying CSS class to Html.DisplayFor (ASP.NET MVC)

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;} 
like image 351
felixgondwe Avatar asked Sep 11 '14 14:09

felixgondwe


1 Answers

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.

like image 60
Chris Pratt Avatar answered Sep 30 '22 19:09

Chris Pratt