1

Using the latest version of MVC, I want to change the style of an item. From reading this question, I thought I could use this code:

@Html.DisplayNameFor(model => model.Adresse, new { style="width:1000px;" })

But it won't change the style of any element. How can I fix this code?

Antoine Pelletier
  • 3,164
  • 3
  • 40
  • 62

3 Answers3

5

I don't think DisplayNameFor renders any HTML elements so adding html attributes to the control won't work.

I would wrap your control with a span and add a CSS class, then add that class to your stylesheet where you can write and manage your styles there.

Something like this:

<span class="display-name">@Html.DisplayNameFor(model => model.Adresse)<span>

Then in your CSS stylesheet add your new class there:

.display-name{
   display:inline-block;
   border: 1px solid #ff0000;
   background-color:#eee;
   font-size:15px;
   /*add more styles ...*/
}
zgood
  • 12,181
  • 2
  • 25
  • 26
  • Yeah, it's pretty much the answer, also i was trying to use the `width` but i realized the right MVC style property is `min-width` , but thats just a detail. – Antoine Pelletier Apr 04 '16 at 18:27
0

Generally this is accomplished by using the htmlAttributes property which is just an anonymous object that contains your preferred styles, just like you have used in your example.

The issue here however is that you are currently attempting to use this with the DisplayNameFor helper as opposed to one that rendered an actual element such as TextBoxFor, TextAreaFor or similar.

The DisplayNameFor helper on it's own will simply render the actual name of the property that you are targeting.

Rion Williams
  • 74,820
  • 37
  • 200
  • 327
-1

Practically the same answer just with some more notes.

use this : @Html.TextBoxFor(p => p.Publishers[0].pub_name, new { @style="width: 1000px" }) notice the space between the : and 1000px. Avoid using semi-colons if you have only one attribute in style.

  • DisplayNameFor function, sorry – Antoine Pelletier Apr 04 '16 at 15:54
  • Why don't you use `@LabelFor()` ? – Yacine Ben Slimene Apr 04 '16 at 15:57
  • I agree the space between `:` and `1000px` looks better, but I don't think it prevents the style from rendering. `width:1000px;` and `width: 1000px;` are the same – zgood Apr 04 '16 at 16:01
  • Also you don't need `@style` for the style attribute. the `@` is really only used for the `class` attribute because `class` is a reserved word. – zgood Apr 04 '16 at 16:07
  • Here is an example I used in one of my applications : `@Html.PasswordFor(m => m.@params[0].data[0].passwd, new { @class = "form-control" ,placeholder = "Mot de Passe", @style = "color: darkgray; width: 200px;"})` This actually works fine. – Yacine Ben Slimene Apr 04 '16 at 16:14