Handlebars Custom Function Demo in .NET MVC

In a Previous post Display Records From Database Using Handlebars in ASP.NET MVC, I discussed how to fetch records from a database and display them using Handlebars. It provides an easy way to convert retrieved data from an Ajax call into HTML without writing lots of custom JS code.

It provides a way to implement simple logic into a template using inbuilt “block functions” like #if but It doesn’t provide a way to perform complex logic directly in a template. Conditional statements which required custom logic must be defined outside of the template. In this article, I’m going to discuss how to create a custom function in handlebars which will be called within the template to perform custom logic.

Creating a custom function
Handlebars provide a registerHelper() function that accepts the name of the custom function. this function will be executed when it will be called. In this article, I made a custom function that will display elements from my array elements, that are greater than 10.
Here, this is my custom function code. you need to add this code into your JS.

Handlebars.registerHelper('isGreater', function (val, options) {
    var fnTrue = options.fn;
    if (val > 10) {
        return fnTrue(this);

This function will check each array element and check that, the element is greater than 10 or not. If the element is greater than 10 then it will return the current context to display.

Here, This is My Full View Code:

This is the view code.
View used in demo

My Script:

This is my jQuery code.
Script used in demo

My Handlebars Template:

This is a handlebars' template
Handlebars’ template used in demo

My Controller Code:

This is the controller code.
Controller used in demo


This is the final output of the demo.
Final output


Submit a Comment

Your email address will not be published. Required fields are marked *


Select Categories