ASP.NET MVC Razor Sample HTML Helper Creation

Simplest example of creating an HTML helper method in Asp.net MVC Razor View

In this example I am creating an helper method to format the currency cuurency color to be red if value is minus and green if value is positive.

Step 1 :

Create the helper function

Step 2 : Create an decimal array

Step 3. Run a loop to get each value of decimal array and call the helper method to format the view.

This is a sample example and can be extended to achieve other goals.

 

@{
 
 var amounts = new List<Decimal> { 12.34m, 12.45m, -12,-19,32.5m,123, 234, -56 };
 
}

<ul>
 @foreach (Decimal amount in amounts )
 {
 <li> @FormatAmount(amount)</li>

 } 
 </ul>


@helper FormatAmount(decimal amount)
{
 var color = "green";
 if (amount < 0 )
 {

 color = "red";
 
 }
 <span style="color:@color">Pending Amount Is : @String.Format("{0:c}", amount)
 
 </span>
 
 
}

Output

helper.