MVC 4.0: Ajax Search with JSON and Client-Side Templates

I talked before about Ajax search but it was using Helper Methods, here we will see how to implement Ajax Search using JSON and Client-Side Templates.

Mustache Client-Side Template

The following code is an example using Mustache, a template library we will use in this post:

<span class="detail">
     Rating: {{AverageReview}}
     Total Reviews: {{TotalReviews}}
</span>

This template would work against an object with AverageReview and TotalReviews properties.
When rendering templates with Mustache, the templates place the values for those properties in their proper location. You can also render templates against an array of data. More documentation for Mustache is available at https://github.com/janl/mustache.js.

To begin writing templates, you can include a script reference to Mustache in the layout view:


<script type="text/javascript" src="~/Scripts/mustache.js"></script>

Now this is where templates come into play. A template is markup embedded inside a script tag. The following code shows a template, as well as the search result markup where the results should display:

<script id="artistTemplate" type="text/html">
<ul>
        {{#artists}}
	<li>{{Name}}</li>

        {{/artists}}</ul>

</script>
<div id="searchresults"></div>

Notice that the script tag is of type text/html.

Modifying the Search Form

We will not use Ajax.BeginForm helper method instead we will write it from scratch.

<form id="artistSearch" method="get" action="@Url.Action("ArtistSearch", "Home")">
    <input type="text" name="q" data-autocomplete-source="@Url.Action("QuickSearch", "Home")" />
    <input type="submit" value="search" />
    <img id="ajax-loader" src="~/Content/Images/ajax-loader.gif" style="display:none"/>
</form>

Without the helper you’ll also need to write your own JavaScript code to request the search result from the server. You’ll place the following code inside your view or place it in outside script file:

$("#artistSearch").submit(function (event) {
    event.preventDefault();
    var form = $(this);
    $.ajax({
        url: form.attr("action"),
        data: form.serialize(),
        beforeSend: function () {
            $("#ajax-loader").show();
        },
        complete: function () {
            $("#ajax-loader").hide();
        },
        error: searchFailed,
        success: function (data) {
            var html = Mustache.to_html($("#artistTemplate").html(),
            { artists: data });
            $("#searchresults").empty().append(html);
        }
    });
});

The to_html method of Mustache combines the template with the JSON data to produce markup. The code takes the template output and places the output in the search results element.

Thank you,
Keep It Simple and Straightforward 🙂
~:H}{H:~

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s