Functions inside page using Razor View Engine – ASP.NET MVC

Posted by hajan on ASP.net Weblogs See other posts from ASP.net Weblogs or by hajan
Published on Sat, 05 Feb 2011 01:35:00 GMT Indexed on 2011/02/05 7:26 UTC
Read the original article Hit count: 530

Filed under:
|
|
|

As we already know, Razor is probably the best view engine for ASP.NET MVC so far. It keeps your code fluid and very expressive.

Besides the other functionalities Razor has, it also supports writing local functions.

If you want to write a function, you can’t just open new @{ } razor block and write it there… it won’t work. Instead, you should specify @functions { } so that inside the brackets you will write your own C#/VB.NET functions/methods.

Lets see an example:

1. I have the following loop that prints data using Razor

<ul>
@{
    int N = 10;
    for (int i = 1; i<=N; i++)
    {
        <li>Number @i</li>
    }    
}
</ul>

This code will print the numbers from 1 to 10:

  • Number 1
  • Number 2
  • Number 3
  • Number 4
  • Number 5
  • Number 6
  • Number 7
  • Number 8
  • Number 9
  • Number 10

So, now lets write a function that will check if current number is even, if yes… add Even before Number word.

Function in Razor

@functions{
    public bool isEven(int number)
    {
        return number % 2 == 0 ? true : false;
    }
}

The modified code which creates unordered list is:

<ul>
@{
    int N = 10;
    for (int i = 1; i<=N; i++)
    {
        if (isEven(@i)) {
            <li>Even number @i</li>
        }
        else {
            <li>Number @i</li>
        }            
    }            
}
</ul>

As you can see, in the modified code we use the isEven(@i) function to check if the current number is even or not…

The result is:

  • Number 1
  • Even number 2
  • Number 3
  • Even number 4
  • Number 5
  • Even number 6
  • Number 7
  • Even number 8
  • Number 9
  • Even number 10

So, the main point of this blog was to show how you can define your own functions inside page using Razor View Engine. Of course you can define multiple functions inside the same @functions { } defined razor statement.

The complete code:

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <title>ASP.NET MVC - Razor View Engine :: Functions</title>
</head>
<body>
    <div>
        <ul>
        @{
            int N = 10;
            for (int i = 1; i<=N; i++)
            {
                if (isEven(@i)) {
                    <li>Even number @i</li>
                }
                else {
                    <li>Number @i</li>
                }            
            }            
        }
        </ul>

        @functions{
            public bool isEven(int number)
            {
                return number % 2 == 0 ? true : false;
            }
        }
    </div>
</body>
</html>

Hope you like it.

Regards,
Hajan

© ASP.net Weblogs or respective owner

Related posts about ASP.NET

Related posts about ASP.NET MVC