8/19/12

Functions in ASP.Net Razor Web Pages


When using Razor Web Pages, it is very common to embed dynamic content on the HTML markup by using a server variable with the following format:

@{
   var message = "Hello";
}

<!DOCTYPE html>

<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title></title>
    </head>
    <body>
        <h1>@message</h1>
    </body>
</html>

This renders a page with a simple hello message. In some instances, we may want the message to be more dynamic and to display a message based on some condition. For those cases, we can leverage the @functions block feature of the Razor syntax. The purpose of this block is to let us add functions that can be called from within the page.  Since each page is defined as a class, we can add functions and properties to support more complex functionality on Web Pages.  Let’s look at this example:

@functions {
    string GetMessage(){
      var req = Request["typ"];
      var message = "Hello";
      if (req=="sales"){
          message ="Welcome to sales";
      }
      else if (req=="support"){         
          message = "Welcome to Support";
      }
      return message;
 }
 
}
 
<!DOCTYPE html>
 
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title></title>
    </head>
    <body>
        <h1>@GetMessage()</h1>
    </body>
</html>

In this example, we call the @GetMessage function which just reads a URL parameter and based on the parameter, it determines what message to display. Notice how the function call is embedded in the markup. To use it, we must proceed it with the @ character which is use to start inline expressions.  To define the function, we use the @functions block directive. In this block we can add functions and properties that can be reused in the page.

The following table shows what query string can be used to load this page and the expected output:

QueryString
Output
Mydomain.com/Page
Hello
Mydomain/Page?typ=sales
Welcome to Sales
Mydomain/Page?typ=support
Welcome to Support

I would suggest using functions on Web Pages for specific functionality on each page. If you want to build functions for common functionality that can be used in several pages, you should add a separate CSHTML page and make the methods static. If you need to reuse blocks of HTML, Razor helpers should be used instead.