22
DecInline CSS and Styles with Html Helpers in MVC3 Razor
Inline CSS and Styles with HTML Helpers: An Overview
In this MVC Tutorial, I am going to explain how can we change the style of HTML Helpers by using CSS. In Asp.Net, we can customize the look and feel of server controls by using CSS class, id, and inline CSS. Similarly, we can change the style of HTML Helpers in MVC Razor.
Inline HTML Helpers
"@helper" syntax is used to create a reusable inline helper method. They make the code more reusable, as well as more readable. Let’s see how to use them.
Read More: MVC Interview Questions and Answers
Step 1: Create an empty ASP.Net MVC Application.
Step 2: Then Right-click the controller and add a controller.
public class HomeController : Controller
{
public ActionResult InlineHTMLHelper()
{
return View();
}
}
Step 3: Right-click the action method and click add view.
@{
Layout = null;
}
@helper OrderedList(string[] words)
{
<ol>
@foreach(string word in words)
{
<li>@word</li>
}
</ol>
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Inline HTML Helper</title>
</head>
<body>
<div>
@OrderedList(new string[]{"Komal","Puja","Saourav","Niha"})
</div>
</body>
</html>
Output
Komal
Puja
Saourav
Niha
In the above code, We made an inline helper method i.e. OrderedList, which takes a string array as an argument and displays each word in an ordered list. We can reuse the inline HTML helpers multiple times on the same view. To access the same inline HTML helper across the different views, we have to move our @helper methods in .cshtml files to the App_Code folder.
@helper OrderedList(string[] words)
{
<ol>
@foreach (string word in words)
{
<li>@word</li>
}
</ol>
@{
Layout = null;
}
!DOCTYPE html>
html>
meta name="viewport" content="width=device-width" />
<title>Inline HTML Helper App Code</title>
</head>
<body>
<div>
@InlineHelplerCode.OrderedList(new string[] { "Komal", "Puja", "Saourabh", "Niha" })
</div>
</body>
</html>
Output
Komal
Puja
Saourabh
Niha
CSS Class
.inputclass
{
width:100px;
height:25px;
}
1. Apply CSS Class to Html Helpers
Suppose the above CSS class is defined in the external style sheet. Now if you want to apply this class to html helpers then we need to add a class name by using @class like :
@Html.TextBox("Name", new { @class="inputclass" })
@Html.TextBoxFor(model => model.Name, new { @class="inputclass" })
2. Apply Inline CSS to HTML Helpers
We can also add inline CSS to html helpers by using styles like:
@Html.TextBoxFor(model => model.Name, new { style="width:100px;height:25px" })
@Html.TextBox("Name", new { style="width:100px;height:25px" })
Summary
I hope you will enjoy these tricks while programming with MVC Razor. I would like to have feedback from my blog readers. Your valuable feedback, questions, or comments about this article are always welcome. Enjoy Coding..!