How to create a custom HtmlHelper Class using declarative @helper syntax in Razor view ?

dhirenkaunar-15094
Posted by dhirenkaunar-15094 under ASP.NET category on | Points: 40 | Views : 2851
In my previous post I have explained how to create custom HtmlHelper Class using Extension Method in ASP.net (MVC2)
In this example I am going to give some example on how to create the Custom HtmlHelper method using declarative @helper syntax in Razor View (MVC3)
There are two way to use declarative @helper syntax to create custom HtmlHelper method
Method 1 :
View Page :
<!DOCTYPE html>
@helper Truncate(string input, int length)
{
if (input.Length <= length)
{
@input
}
else
{
@input.Substring(0, length) .....
}
}
<html>
<head>
<title>Index</title>
</head>
<body>
<div>
Original Text : @ViewBag.Message <br />
Text after Truncate :@Truncate(ViewBag.Message as string,15)
</div>
</body>
</html>

Method 2 : We will archive the above code by creating a file with .cshtml extension inside the app_code folder and adding Declarative @Helper syntax inside that as mentioned below example.
Declarative @Helper class : App_code\CustomHelper.cshtml

@helper Truncate(string input, int length)
{
if (input.Length <= length)
{
@input
}
else
{
@input.Substring(0, length) .....
}
}
View Page :
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
</head>
<body>
<div>
Original Text : @ViewBag.Message <br />
Text after Truncate :@CustomHelper.Truncate(ViewBag.Message as string,15)
</div>
</body>
</html>
output :
Original Text : Razor declarative @helper example
Text after Truncate : Razor declarati......

Comments or Responses

Login to post response