Display Records From Database Using Handlebars in ASP.NET MVC

In this article, we are going to see What is Handlebars.js and what is the use of it?

Roadmap for developing the application

  • What is HandleBars?
  • Integrating HandleBars in ASP.NET MVC5

What is HandleBars?

Handlebars is a simple templating language. They uses template and input object to generate the HTMLs. You can see more about HandleBars from their offical website from here.

Integrating HandleBars in ASP.NET MVC5

The below article is about Handlebars. How to display records from database using handlebars in .Net MVC.

So, let’s start it…..

Step 1: Create ASP.NET Web Application(MVC) and give it a name.

Step 2:

  1. Download Handlebar.js from here https://handlebarsjs.com/installation/#npm-or-yarn-recommended
  2. Add a downloaded link to our newly created project.

Step 3: Now add a new controller Named Handlebars.

  1. Create methods for the view to display employee’s details and to fetch records from the database.
  2. Add view to display the employee’s details.
  3. Now create a partial view, add script tag and give attribute id and type=”text/x-handlebars-template” and design it as you want.
  4. Render this partial view to our view.

Here is my full Controller code:

In the GetEmployeDetails method, I’m fetching the record from the database using the .net entity framework and return it to the view side.

HandlebarsController.cs

public class HandlebarsController : Controller
    {
        ChandEntities db = new ChandEntities();
        public ActionResult Employee()
        {
            return View();
        }

        [HttpPost]
        public JsonResult GetEmployeeDetails()
        {
            try
            {
                List<Employee> emp = new List<Employee>();
                emp = db.Employees.ToList();
                if (emp != null)
                {
                    return Json(new { IsSuccess = true, Message = "Details fetched successfully..", Data = emp }, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    return Json(new { IsSuccess = true, Message = "Table is Empty.." }, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                return Json(new { IsSuccess = false, Message = "Something went wrong" }, JsonRequestBehavior.AllowGet);
            }
        }
    }

Code for Employee.cshtml file:

In the script section, attach Handlerbars.js and jquery.min.js here. on page load, I make an ajax call to get records. In response, if get records then I’m displaying it using handler.

@{
    ViewBag.Title = "Employee";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>
    Employee Details
</h2>
<div>
    <table class="table table-hover table-striped table-bordereless">
        <thead>
            <tr>
                <th>Employee Id</th>
                <th>First Name</th>
                <th>Last Name</th>
                <th>Email</th>
                <th>Address</th>
                <th>City</th>
            </tr>
        </thead>
        <tbody id="TableBody">
            @Html.Partial("~/Views/Handlebars/HandlebarsTemplate.cshtml")
        </tbody>
    </table>
</div>
@section scripts{
    <script src="~/Scripts/jquery-3.3.1.min.js"></script>
    <script src="~/Scripts/handlebars-v4.7.6.js"></script>
    <script>
        $(document).ready(function () {
            $.ajax({
                url: "/Handlebars/GetEmployeeDetails",
                type: 'POST',
                async: false,
                success: function (result) {
                    if (result.IsSuccess) {
                        if (result.Data.length > 0) {
                            alert(result.Message);

                            // CODE FOR HANDLEBARS
                            var HandlerbarTemplate = $("#EmployeeDetailsTemplate").html(); // GET TEMPLATE
                            var CompileHtml = Handlebars.compile(HandlerbarTemplate);
                            var EmployeeDetailHTML = CompileHtml({ EmployeeDetail: result.Data }); //SET RECORD LIST TO HANDLEBARS OBJECT
                            $('#TableBody').append(EmployeeDetailHTML); // APPEND HTML TO TABLE BODY
                        }
                        else {
                            alert(result.Message);
                        }
                    }
                    else {
                        alert("Please try again!!");
                    }
                }
            });
        });
    </script>

}

Code for HandlebarsTemplate.cshtml file

To use the handler we need to provide id and type=”text/x-handlebars-template” to script tag. {{#EmployeeDetail}} is an array of the objects of records. EmployeeId, FirstName, LastName, Email, Address, City are the table fields that I want to display. Everything which we want to display, we must write it in between {{#EmployeeDetail}} and {{/EmployeeDetail}}.

<script id="EmployeeDetailsTemplate" type="text/x-handlebars-template">
    {{#EmployeeDetail}}
    <tr>
        <td>
            {{EmployeeId}}
        </td>
        <td>
            {{FirstName}}
        </td>
        <td>
            {{LastName}}
        </td>
        <td>
            {{Email}}
        </td>
        <td>
            {{Address}}
        </td>
        <td>
            {{City}}
        </td>
    </tr>
    {{/EmployeeDetail}}
</script>

Output:

display-records-from-database-using-handlebars-in-asp-net-mvc-output

Submit a Comment

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

Subscribe

Select Categories