Hello,
Ajax Control Toolkit has been in existence for a very long time and have I started working with this toolkit since ASP.NET 2.0 thru 3.5. However, it's popularity declined when jQuery UI and other JavaScript frameworks came into existence. For this demo, I'll integrate the AutoCompleteExtender control in an empty project given that you will use the toolkit in your ASP.NET 4.5 Web Forms website.
1. Create an ASP.NET Webforms Project using Visual Studio 2012 or 2013 and then install AjaxControl Toolkit using Nugget
PM> Install-Package AjaxControlToolkit
2. Add an ADO.NET Entity Framework that connects to AdventureWorks Database and CountryRegions table.
3. Add a new Webform page (Default.aspx)
HTML Code:
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager>
<asp:TextBox ID="txtCountries" runat="server"></asp:TextBox>
<ajaxToolkit:AutoCompleteExtender ID="AutoCompleteExtender1" CompletionListCssClass="autocomplete_completionListElements" runat="server" CompletionSetCount="10" TargetControlID="txtCountries"
ServiceMethod="GetCountries" CompletionInterval="100" EnableCaching="false" MinimumPrefixLength="1">
</ajaxToolkit:AutoCompleteExtender>
</div>
</form>
4. Add the following snippet below in Code Behind (Default.aspx.vb)
VB.NET Code:
Private Shared _context As AdventureWorksEntities 'Entity Framework
<ScriptMethod>
<WebMethod>
Public Shared Function GetCountries(prefixText As String, count As Integer) As List(Of String)
_context = New AdventureWorksEntities()
Dim result = (From country In _context.CountryRegions.AsEnumerable()
Where country.Name.ToLower().StartsWith(prefixText, StringComparison.OrdinalIgnoreCase)
Select country.Name).Take(count)
Return result.ToList()
End Function
<ScriptMethod>
<WebMethod>
Public Shared Function GetCountryInfo(Country As String) As Object
_context = New AdventureWorksEntities()
Dim result = (From countryObj In _context.CountryRegions.AsEnumerable()
Where countryObj.Name.ToLower().Equals(Country.ToLower())
Select New With {
.Name = countryObj.Name,
.CountryRegionCode = countryObj.CountryRegionCode
}).FirstOrDefault()
Return result
End Function
5. To capture selected country, add the JavaScript code in your page that handles the blur event of the textbox.
JavaScript Code:
<script type="text/javascript">
$(document).ready(function () {
$('[id$=txtCountries]').blur(function (event) {
var country = $(this).val();
$.ajax({
url: "Default.aspx/GetCountryInfo",
data: '{ Country: "' + country + '"}',
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.d != null) {
var c_name = data.d.Name;
var c_code = data.d.CountryRegionCode;
alert('Code: ' + c_code + ', Name: ' + c_name);
}
},
error: function (a, b, c) {
alert("Error in Retrieving Record!");
}
});
});
});
</script>
Regards,
kgc