CodeDigest.Com Logo
Featured:

Displaying JSON Data Using jQuery Templates (mustache.js) in Asp.Net MVC

Tagged as: Asp.Net MVC Posted By

Getting Json data and displaying it in a webpage is very common requirement these days. jQuery library simplified the client side scripting and has many methods to manipulate Json strings. Though it is sufficient to just use the jQuery library to get and display Json data, there are some template libraries available to display Json data in any format we require. In this article, let’s use a library called mustache.js to display Json data in a MVC view.

For easy understanding, let’s build an Employee master-details view and use mustache.js templates to display the Employee details when the user clicks details against each row.

Assuming, you have an Asp.Net MVC 5.0 project created using Visual Studio 2017(or 2017), let’s go ahead and create the action method to return employee details as Json string.

public JsonResult detailasjson(int id)
{
    Employee emp = db.Employees.Where(e => e.EmployeeId == id).FirstOrDefault();
    return Json(emp, JsonRequestBehavior.AllowGet);
}
 

Let’s now add the latest mustache.js library into our project. You can use either Bower or Nuget package manager to do this. The below image shows mustache.js installed using Nuget package manager in Visual Studio 2015.

 

Next, let’s build the template using mustache syntax and use jQuery Ajax to get the Json from the controller action method and display it. The below HTML snippet has the mustache tamplate with id employeeDetailTemplate enclosed in a <script> tag. The Mustache library uses the format {{ json.propertyname }} commonly called as binding expressions to display a Json property as seen below.

EmployeeSummary.cshtml

@* Removed for brevity *@
<script id="employeeDetailTemplate" type="text/html">
    <h2>Employee Details Using Templates</h2>
    <dl class="dl-horizontal">
        <dt>First Name</dt>
        <dd>{{emp.FirstName}}</dd>

        <dt>Last Name</dt>
        <dd>{{emp.LastName}}</dd>

        <dt>Address1</dt>
        <dd>{{emp.Address1}}</dd>

        <dt>Address2</dt>
        <dd>{{emp.Address2}}</dd>

        <dt>City</dt>
        <dd>{{emp.City}}</dd>

        <dt>State</dt>
        <dd>{{emp.State}}</dd>

        <dt>Country</dt>
        <dd>{{emp.Country.Name}}</dd>

        <dt>Postal Code</dt>
        <dd>{{emp.PostalCode}}</dd>

        <dt>Email</dt>
        <dd>{{emp.Email}}</dd>

        <dt>Date Of Birth</dt>
        <dd>{{emp.DOB }}</dd>

        <dt>Gender</dt>
        <dd>{{emp.Gender}}</dd>

        <dt>Salary</dt>
        <dd>{{emp.Salary}}</dd>

        <dt>Project Manager for</dt>
        <dd>
            <ul>
                {{#emp.Projects}}
                <li>{{Name}}</li>
                {{/emp.Projects}}
            </ul>
        </dd>

    </dl>
</script>

<div id="details">

</div>

@section scripts {
    <script src="~/Scripts/mustache.js"></script>
    <script type="text/javascript">

        $(document).ready(function () {
            $('a.details').click(function () {
                var id = $(this).attr("id");
                $.ajax({
                    url: '/employee/detailasjson', type: "GET", dataType: "json",
                    data: { id: id },
                    success: function (data) {
                        var html = Mustache.to_html($("#employeeDetailTemplate").html(), { emp: data });
                        $("#details").html(html);

                    },
                    error: function (xhr, status, error) {
                        alert(xhr.responseText);
                        alert(status);
                        alert(error);
                    }
                });

           });
           
        });

    </script>
}
 

 

The method Mustache.to_html(htmlElement, json) will use the Json data and populate the template passed to it to return the final html.

Mustache.to_html($("#employeeDetailTemplate").html(), { emp: data });

The other special thing in the above template is parsing and displaying the nested Json list in the html. The Employee objects has list of projects the employee is part is displayed using                 {{#emp.Projects}}   {{/#emp.Projects}} which iterates the json list to display each project. Code below for reference. Refer the sample Json string with list of projects bolded included below for reference.

<dt>Project Manager for</dt>
        <dd>
            <ul>
                {{#emp.Projects}}
                <li>{{Name}}</li>
                {{/emp.Projects}}
            </ul>
        </dd>
 

Sample Json returned by detailsasjson() action method

{"Country":{"CountryId":215,"Name":"United States"},"Department":{"DepartmentId":1,"DepartmentName":"IT"},"Projects": [{"ProjectId":1,"Name":"HRMS","EmployeeId":1},{"ProjectId":2,"Name":"HMS","EmployeeId":1}],"EmployeeId":1, "DepartmentId":1,"FirstName":"Tom","LastName":"Hanks","Address1":"1St Street","Address2":"Columbia Ave","City":"Los Angeles","State":"CA", "CountryId":215,"PostalCode":"123456","Email":"tom@gmail.com","ConfirmEmail":"tom@gmail.com", "DOB":null,"Gender":"Male","IsPermanent":false,"Salary":0}

 

Using Template File from Server

In the above code, we have defined the template inside the view directly. Sometimes, we many need to put the template in an external template file (say for example EmpDetails.html) and use it to render the template. For doing this, include a HTML file in the solution and move the template content (<script id="employeeDetailTemplate" type="text/html"> </script>) into it. The modified code to use the template from an external template is below.

@section scripts {
    <script src="~/Scripts/mustache.js"></script>
    <script type="text/javascript">

        $(document).ready(function () {
            $('a.details').click(function () {
                var id = $(this).attr("id");
                $.ajax({
                    url: '/employee/detailasjson', type: "GET", dataType: "json",
                    data: { id: id },
                    success: function (data) {
                        $.get('/Scripts/templ/EmpDetails.html', function (templates) {
                            var template = $(templates).filter('#employeeDetailTemplate').html();
                            $('#details').html(Mustache.render(template, { emp: data }));

                        });
                    },
                    error: function (xhr, status, error) {
                        alert(xhr.responseText);
                        alert(status);
                        alert(error);
                    }
                });

           });
           
        });

    </script>
}
 

Download the source and see it in action!



Feedback

Comments