How to Apply Styles with Html Helpers in MVC4 Razor

In this article let us discussย how to apply CSS styles usingย HTML helpers.

  • using Inline
  • using Class

Using Inline CSS

From the below code, we can directly add the styles.

@Html.TextBox(“Name”, “”, new{style = “width:80px;height:20px;background-color:#F0F0F0 ;”})

using CSS Class

Another way, we can call theย css class name instead of style.

.txtbox {
width: 100px;
height: 75px;
background-color: #F0F0F0;
border:1px solid black;
}

@Html.TextBox(“txtName”,””, new{@class = “txtbox”})

Note :

Correct Way:

@Html.TextBox(“txtName”,””, new{@class = “txtbox”})

Wrongย Way:

@Html.TextBox(“txtName”, new{@class = “txtbox”}) – It will not apply the style to the textbox

From the above code new{@class = “txtbox”} want to be third parameter , if you not going to pass the value asย second parameter then we need pass null/Empty value.

Output:

Inline style for textbox