AutoCompleteExtender with WCF using Entity Framework






4.80/5 (5 votes)
AutoCompleteExtender with WCF
AutoCompleteExtender
is an extender available in AjaxControlToolkit which can be attached to any TextBox
control.When user enters a characters in TextBox which is extended by AutoCompleteExtender, AutoCompleteExtender pulls out the words that starts with the contents of the TextBox from database or specified memory location and display them in popup list. It enables ASP.NET TextBox
control to behave like a search box.
Goal
In general ASP.NET Webservices are used with AutoCompleteExtender
to display the results. WCF provides rich support to build services for Ajax and Silverlight clients with different attributes and different hosting classses. It is easy to build this kind of services, because we have Ajax enabled WCF service template which is provided in Visual Studio 2010 and above, automates the entire process of developing WCF services. Performance wise WCF services are faster than Webservices and we can use light weight message exchange format like JSON with WCF services. So the WCF services can be used with AutoCompleteExtender to produce quick and efficient results.
Using the code
Create table Names to store
Id
(int type primary key) andName
(varchar type) in SQL Server database using SQL Server Mangement Studio- Create New website Project
Goto File -> New -> Website -> Select Visual C# under Templates
-> Select ASP.NET Empty Website template -> Click OK - Adding Entity Data Model.
- Goto Solution Explorer -> Right click on Website -> Goto Add -> Goto Add New Item -> Select ADO.NET Entity Data Model -> Click on OK
- In Entity Data Model Wizard.
Select Generate from databse option -> Click on Next -> Click on New Connection -> Provide required fields in Connection Settings window -> Click on OK -> Select 'Yes, include the sensitive data in the connection string.' radiobutton -> Check 'Save entity connection string in Web.config as' checkbox and writeMYDBEntities
in following textbox -> Click on Next -> Click on Tables -> Add Names table -> Give Model Namespace name as
-> Click on Finish -> Build the project.MYDBEntities
- Result :- This process will generate
Model.context.cs
andModel.cs
class in App_Code folder.
Context class :- Enables us to perform CRUD operations on table usingDbSet
class.
Model class :- Contains Names entity from database which is converted into class.
-SometimesModel.context.cs
andModel.cs
classes will not create. In such case follow the following troubleshoot procedure
Right click onModel.context.tt
andModel.tt
-> Run Custom tool
This will generateModel.context.cs
andModel.cs
class in App_Code folder.
-Check for ConnectionString in web.config file. If it is not added then addconnectionString
in Configuration tag as follows<connectionStrings> <add name="MYDBEntities" connectionString="metadata=res://*/App_Code.Model.csdl|res://*/App_Code.Model.ssdl|res://*/App_Code.Model.msl;provider=System.Data.SqlClient;provider connection string="data source=.;initial catalog=MYDB;user id=sa;password=123;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" /> </connectionStrings>
-
Preparing Ajax enabled WCF service.
-
Goto Solution Explorer -> Right click on website -> Goto Add -> Goto Add New Template -> Select Ajax Enabled WCF Service Template -> Click on OK.
Result :-
-A regularService.svc
file added to App_Code.
-No interface only classService.cs
.ServiceContract
is written directly for class.
-In web.configwebHttpBinding
endpoint along withenableWebScript
behavior -
In
Service.cs
file writeOperationContract
as required. In this example class Service written as follows.
[ServiceContract(Namespace = "")] [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] public class Service { [OperationContract] //Specifying message exchange format is JSON [WebInvoke(ResponseFormat=WebMessageFormat.Json)] public List<string> GetNames(string prefixText) { MYDBEntities obj=new MYDBEntities (); var x = from n in obj.names where n.name.Substring(0,prefixText.Length).ToLower()==prefixText.ToLower() select n; List<string> name = new List<string> (); foreach (var item in x) { name.Add(item.name.ToString()); } return name; } }
-Specify
ResponseFormat
parameter ofWebInvoke
attribute asWebMessageFormat.JSON
to specify the message exchange format as JSON.
-Method nameGetNames
can be replaced with name of your choice, but the return type and parameter name and type must exactly match including case.
-GetNames method is value returning method, it returns list of names from Names table which matched with characters contains inprefixText
parameter.
The above service can not be tested as it requires metadata. To test this service add an endpoint withmexHttpBinding.
-
Goto Solution Explorer -> Right click on website -> Goto Add -> Goto Add New Template -> Select Ajax Enabled WCF Service Template -> Click on OK.
- Assuming that AjaxControlToolKit.dll is already added to the project and registered in web.config file as following in system.web tag
- Add one
appSettings
tag in Configuration tag as follows to setUnobtrusiveValidatonMode
to false - Add ASP.NET empty website template to the website project and name it as Deafault.aspx. In source view of Default.aspx write the following code.
- In
head
tag addcomletionList
,item
anditemHighLight
css classes instyle
tag
.completionList { padding:0px; margin:0px; color:black; overflow:auto; text-align:left; border:2px solid lightskyblue; list-style-type:none; cursor:default; height:200px; } .item { height: 17px; cursor:pointer; } .itemHighLight{ color:White; background-color:lightskyblue; cursor:pointer; }
The above css classes is added to use with
CompletionListCssClass
,CompletionListItemCssClass
andCompletionListHighlightedItemCssClass
property of AutoCompleteExtender . It will apply on popup list while displaying the search result. - Now in
form
tag of Default.aspx page. Add oneTextBox
withAutoCompleteExtender
as follows<form id="form1" runat="server"> <ajaxToolkit:ToolkitScriptManager runat="server"></ajaxToolkit:ToolkitScriptManager> <div> <b>Enter Name:</b> <asp:TextBox ID="txtName" runat="server"></asp:TextBox> <ajaxToolkit:AutoCompleteExtender ID="ace1" TargetControlID="txtName" runat="server" ServiceMethod="GetNames" ServicePath="Service.svc" EnableCaching="true" MinimumPrefixLength="1" CompletionListCssClass="completionList" CompletionListItemCssClass="item" CompletionListHighlightedItemCssClass="itemHighLight"></ajaxToolkit:AutoCompleteExtender> </div> </form>
Properties Description TargetControlID
The TextBox control where the user types content should be automatically populated. ServiceMethod
The WCF service method to be called. ServicePath
The path to the WCF service that the extender uses to produce the result. MinimumPrefixLength
Minimum number of characters that must be entered before getting suggestions from the WCF service. CompletionInterval
Time in milliseconds. After each interval AutoCompleteExtender get suggestions from WCF webservice. EnableCaching
Specifies client side caching is enabled or not
CompletionListCssClass
Css class that will be used to style the completion list layout. CompletionListItemCssClass
Css class that will be used to style an item in autocomplete list. CompletionListHighlightedItemCssClass
Css class that will be used to style a highlighted item in the completion list. - In
- Run the website to check the following output
<pages>
<controls>
<add tagPrefix="ajaxToolkit" assembly="AjaxControlToolkit" namespace="AjaxControlToolkit"/>
</controls>
</pages>
<appSettings>
<add key="ValidationSettings:UnobtrusiveValidationMode" value="none"/>
</appSettings>

Points of Interest
- Using Ajax Enabled WCF service to test the AutoCompleteExtender.
- Using Entity Framework to get the records from database.