I am using the following code to display text from my view model in my view:
@Html.DisplayFor(m => m.Name)
When I look at the HTML details in IE9 (which I have to use at work) there is no class associated with the name, it just uses the Body CSS styling instead of the display-field class styling. Does anyone know what might be causing this issue or how I might edit the CSS for the text created?
DisplayFor is used for templating reasons. If you aren't using a template, then you should just use the item like so: @Model.Name
If you want to give it a class or id, then you need to wrap it in a span or div.
Your problem is that you're using the wrong method to output data, and expecting it to do something else. There is no built-in way to output raw data with class names.
So your choices are, wrap the raw item in a container that you can apply the css to, or create a template to use for these, then specify the template name in the DisplayFor like so:
@Html.DisplayFor(m => m.Name, "NameTemplate")
if it is a label, use proper helper for it as Nataka526 suggests
otherwise put it in a span with a class and update css for that class:
your html:
<span class="name">
@Html.DisplayFor(m => m.Name)
</span>
your css:
.name {
//custom css
}
UPDATE
Another option:
Update your Display Templates to handle a specific ViewData key:
in Views > Shared > DisplayTemplate (create this folder if you don't have it already):
add file String.cshtml:
@model string
@{
string myClass = ViewData["class"]
}
@if(string.IsNullOrEmpty(myClass))
{
@:@Model
}
else
{
<span class="@myClass">@Model</span>
}
you may need to add DisplayTemplates for other tipes as well besides string.
In the view you will write something like this:
@Html.DisplayFor(m => m.Name, new { @class= "name" })
This will add spans around it automatically.
UPDATE
Explanation:
There is an overload on Html.DisplayFor
which accepts two parameters: expression and object additionalViewData
. So the second parameter that I pass is that anonymous object additionalViewData. I create this object with property called class
Inside of the html helper I then check if there is a ViewData with a key class
and if there is, I put output inside a span with that class value.
**
updated variable name from class
to myClass
since "class" is not appropriate variable name.