Using Razor Engine Functions and Helpers

in #utopian-io8 years ago (edited)

What Will I Learn?

How To Use Razor Engine Functions and Helpers

Requirements

  • Razor Engine
  • .NET framework
  • ASP.NET MVC framework

Difficulty

Intermediate

Tutorial Contents

  • Overview of Functions
  • Functions in C#
  • Functions in VB
  • Overview of Helpers
  • Helpers in C#
  • Helpers in VB
  • Global Helpers

Using Razor Engine Functions and Helpers

In ASP.NET MVC, the Html.Action helper method added the ability to invoke an action method. The contents of the action result rendered in the current HTTP response at the spot that it was declared. This was yet another way of rendering inline content, which it provided similar results as a partial view would, but varied in its implementation. For instance, a partial view renders with a given model, where the Html.Action method actually directly invokes an action using routing parameters. Both techniques provide additional ways to create reusable nuggets of user interface that could be repeated throughout.

The Razor engine offers something similar to this through the use of functions and helpers. Functions are properties or methods defined within a view that can be called throughout. A function can be thought of as creating a property or method in a code-behind page of a web form. Helpers, on the other hand, define a template that can be injected into the response stream at the point of its invocation. Helpers can be defined locally to the view or globally.

We're going to examine these capabilities and view how we can leverage them as developers.

Overview of Functions

Functions are properties or methods that are available throughout life of the view. A property on the view is accessible throughout the view, and its value is persisted like any other property value within the current request (but are lost between requests unless persisted in session, cache or some other state mechanism). In addition, methods also provide some service to the view, in that they accept work just like any other method in the .NET framework for any class. It can work with the input that's provided to it or with the base view (to a more limited extent in comparison to what was possible with web forms, since web forms has a complete API for the view).

If a method needs to render content to the view, it can do so in the traditional MVC approach using the IHtmlString interface. Under the scenes, MVC used an HTML string to represent markup rendered in the browser. This interface is the core representation of HTML content used by all HTML helpers in the ASP.NET MVC framework, and can be used here too to represent HTML content.

Functions in C#

Functions in C# are defined in a code block with a special functions keyword. Take a look of an example in Listing 1. Functions fully support the C# syntax; no new special conventions are used within the functions code block. Functions are defined directly in the view.

Listing 1: Defining Properties and Methods

@functions {
    private DateTime _executionDate = DateTime.Now;
    public DateTime ExecutionDate
    {
        get { return _executionDate; }
        set { _executionDate = value; } 
    }
    public IHtmlString GetFunctionMessage()
    {
        return new HtmlString("This is my function message.");  
    }
}

As you can see, properties and methods work like they would if they were defined in the code behind class of a web form. The property wrapper can work with private variables, and methods can be defined returning HTML strings, integers, or any other types of data.

Functions in VB

Functions in VB also work using a code block with the @Functions keyword at the beginning, and an End Functions declaration at the end, similar to code blocks in VB. Functions have the same purpose in VB as they do in C#. Take a look at the VB equivalent of Listing 1, which appears in Listing 2.

Listing 2: Functions in VB

@Functions
    Private _executionDate As DateTime = DateTime.Now
    Public Property ExecutionDate() As DateTime
        Get
            Return _executionDate
        End Get
        Set(ByVal value As DateTime)
            _executionDate = value
        End Set
    End Property
    Public Function GetFunctionMessage() As IHtmlString
        Return New HtmlString("This is my function message.")
    End Function
End Functions

Notice that all of the conventions still rely on the standard VB syntax for blocks of code, with a beginning Functions statement, ending with an End Functions statement.

Overview of Helpers

Helpers are defined using the @helper special keyword. A helper specifies a name to its method, defines a list of parameters, and is called like a method, but functions quite differently as it has no return value. A helper directly renders its contents, which consists of client and server content that's rendered directly where the helper is called.

Helpers reside directly in the view that needs it (with the exception of Global Helpers discussed later). A helper is directly accessible within the view it's defined by calling it like any other method in the system.

Helpers in C#

Helpers in C# have similarities and differences in comparison with functions. For instance, both define a signature of a method; yet helpers do not define a return type, and define the client and server content directly within its body. Helpers also can define a variety of mixing client and server content, which is convenient in that a helper defines its template directly, instead of having to concatenate markup together like a helper would.

Listing 3: Helpers in C#

@helper TextDecorator(string text)
{
    if (!string.IsNullOrWhiteSpace(text))
    {
        <span class='Decorated'>
            @text
        </span>
    }
    else
    {
        <text>
             
        </text> 
    }
}

One of the harder concepts to understand is how flexible Razor is. Within the helper definition is functionality that acts similarly to a code block, supporting if/else and a variety of other constructs. Within this, template definitions by defining client-side markup is completely supported, as well as defining server-side statements within the client-side markup, all within a server-side helper.

Helpers in C# are invoked like a method, such as: @TextDecorator("This is my text.").

Helpers in VB

Helpers in VB use VB syntax again to define the start and end of the helper code block. All templates rendered to the UI in VB must define an @ character at the beginning of the template. This is a VB only requirement. Other than the VB syntax and defining templates with an @, everything else in a helper is the same.

Listing 4: Helpers in VB

@Helper TextDecorator (text As String)
    If (Not String.IsNullOrWhiteSpace(text)) Then
        @<span class='Decorated'>@text</span>
    Else
        @<text> </text> 
    End If
End Helper

Helpers in VB are invoked like a method, such as: @TextDecorator("This is my text.").

Global Helpers

Global helpers work the same as local helpers. Global helpers, instead of being defined in the view, reside in the App_Code folder. Global helpers follow the convention .. For instance, if a view GlobalHelpers.cshtml resides in the App_Code folder and has a helper named PageHeader, this helper could be invoked via the statement GlobalHelpers.PageHeader().

Global helpers provide an easy way to centralize UI nuggets to use throughout the entire application, and provide a consistent way to standardize application features like page or section titles, common data elements (such as a first and last name being rendered as "Last, First") and much, much more.

Conclusion

Functions and helpers is a feature to Razor that allows standardization throughout an application. Helpers and functions can achieve UI standardization and provide a reusable nugget that can be invoked throughout the application. Functions work similarly to a .NET function and return any type of data, whereas a helper defines the template inline, working similarly as a partial view, with the model passed as parameters.



Posted on Utopian.io - Rewarding Open Source Contributors

Sort:  

Thank you for the contribution. It has been approved.

You can contact us on Discord.
[utopian-moderator]

@elissa, No matter approved or not, I upvote and support you.

Hey @elissa I am @utopian-io. I have just upvoted you!

Achievements

  • You have less than 500 followers. Just gave you a gift to help you succeed!
  • Seems like you contribute quite often. AMAZING!

Suggestions

  • Contribute more often to get higher and higher rewards. I wish to see you often!
  • Work on your followers to increase the votes/rewards. I follow what humans do and my vote is mainly based on that. Good luck!

Get Noticed!

  • Did you know project owners can manually vote with their own voting power or by voting power delegated to their projects? Ask the project owner to review your contributions!

Community-Driven Witness!

I am the first and only Steem Community-Driven Witness. Participate on Discord. Lets GROW TOGETHER!

mooncryption-utopian-witness-gif

Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x

Coin Marketplace

STEEM 0.12
TRX 0.34
JST 0.032
BTC 113130.33
ETH 4169.93
USDT 1.00
SBD 0.78