Monday, October 11, 2010

Code: jQuery AJAX and Templates

The jQuery Templating plugin Microsoft’s web team has been working on has been accepted by the jQuery team check out the code below for usage with an AJAX web service.

1.  Reference jQuery 1.4.2 or later, and the template .js file (Templates will be an included part of jQuery 1.5)

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<
script type="text/javascript" src="/Scripts/jquery.tmpl.js"></script>


2.  create the template that will be applied to each item in your result set, notice the ${} syntax



<script id="clientTemplate" type="text/html">
<li><a href="Detail.aspx?q=${Id}" target="_blank">${Description}</a></li>
</script>


3.  Give the DOM element that will house the template an ID



<div>
<
ul id="MatchingQuestions">
</
ul>
</
div>


4.  Create the AJAX Call to your web service.  Notice that it is binding to the “d” element of the resulting msg object.



function SearchQuestions(text) {
$.ajax({
type: "POST",
url: "/NotifierWS.asmx/SearchQuestions",
data: "{'searchText': '" + text + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$("#clientTemplate").tmpl(msg.d).appendTo("#MatchingQuestions");
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.statusText);
}
});
}


5. Create a web service method (the service class will also need to have the ScriptService attribute)


[WebMethod]
public QuestionItem[] SearchQuestions(string searchText)
{
List<QuestionItem> result = new List<QuestionItem>();
foreach (Business.Question q in Business.Question.SearchQuestions(searchText, 5))
{
result.Add(new QuestionItem(){ Id = q.Id, Description = q.Title});
}
return result.ToArray();
}


public class QuestionItem
{
public long Id { get; set; }
public string Description { get; set; }
}