I am using JQuery UI Autocomplete with my ASP.NET-C# Website.
JavaScript:
$(function () {
var availableTags = [
<%=GetAvaliableTags() %>
];
$("input.tag_list").autocomplete({
source: availableTags
});
});
C# Function in code-behind:
public string GetAvaliableTags()
{
var tags = new[] { "ActionScript", "Scheme" };
return String.Join(",", tags.Select(x => String.Format("\"{0}\"", x)));
}
This is working fine. But I have a doubt that if I fetch the big amount of tags from database, it will load all those tags on page load at once, making it slow. The efficient way that came to my mind is to use Ajax. But I am not a Ajax programmer and know little about it. Can any one please tell me how to do it with Ajax efficiently? How to call GetAvailableTags
on demand?
UPDATE
I tried like this:
$(function () {
var availableTags = [function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "CreateTopic.aspx/GetAvaliableTags",
data: "{ 'key' : '" + $("input.tag_list").val() + "'}",
dataType: "json",
async: true,
dataFilter: function (data) { return data; },
success: function (data) {if (result.hasOwnProperty("d")) {
$("input.tag_list").autocomplete({
source: result.d
});
}
else {
// No .d; so just use result
$("input.tag_list").autocomplete({
source: result
});
});
}];
$("input.tag_list").autocomplete({
source: availableTags
});
});
Web Method equivalent of GetAvailableTags()
[System.Web.Services.WebMethod]
public static string GetAvaliableTags(string key)
{
var tags = new[] { "ActionScript", "Scheme" };
return String.Join(",", tags.Select(x => String.Format("\"{0}\"", x)));
}
But the Ajax call is not being fired. What can be the reason?
I would recommend using an ASP.NET AJAX Page Method on the server-side and have the jQuery .ajax()
function call it to retrieve the data, like this:
Code-behind:
[WebMethod]
public static string GetAvailableTags()
{
// Put logic here to return list of tags (i.e. load from database)
var tags = new[] { "ActionScript", "Scheme" };
return String.Join(",", tags.Select(x => String.Format("\"{0}\"", x)));
}
Markup:
$(document).ready(function() {
$.ajax({
type: "POST",
url: "PageName.aspx/GetAvailableTags",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(result) {
if (result.hasOwnProperty("d")) {
// The .d is part of the result so reference it
// to get to the actual JSON data of interest
$("input.tag_list").autocomplete({
source: result.d
});
}
else {
// No .d; so just use result
$("input.tag_list").autocomplete({
source: result
});
}
}
});
});
Note: You will need to change the name of
PageName.aspx
to the name of your .aspx page. Also, the.d
syntax was an anti-XSS protection put in by Microsoft in the ASP.NET 3.5 release of ASP.NET AJAX; therefore the check to see if the.d
property is there or not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With