Telerik Telerik
The Telerik Blogs

How To: Use WCF services with ASP.NET AJAX databound controls

Wednesday, April 08, 2009 by ASP.NET AJAX Team | Comments 6

As you know RadControls for ASP.NET AJAX controls fully leverage .NET 3.5 and come with built-in support for LINQ, LinqToSQL, EntityDataSource, ADO.NET DataServices, and WCF Web Service. With Q1 2009 our online examples feature .NET 3.5 examples for all databound controls (Grid, Scheduler, ComboBox, Menu, TreeView, PanelBar).

In this post I will guide you through the process of creating a RadComboBox which loads its items on demand using WCF services. This will be a step by step tutorial, but if you are familiar with the process you can jump directly to the onilne demo.

The steps below show how to load the items of RadComboBox from WCF service but they are also applicable for RadMenu and RadTreeView.

1. Create a new Web Site in Visual Studio 2008. Make sure the target framework is set to 3.5

2. Drag RadComboBox from your toolbox. From the SmartTag click on the Add RadScriptManager link. It will automatically register the handler in the web.config file.

combo-smart-tag

handler-added

 

3. Add the WCF service – right click on your project in the Solution Explorer and select Add New Item. This is important: select the Ajax-enabled WCF service option (do not mix it with WCF Service):

adding-wcf-service 

Clicking the Add button will create the .svc file as well as the code behind file placed in the App_Code folder. The web.config file is also automatically updated with the appropriate system.serviceModel node:

<system.serviceModel>
    <behaviors>
      <endpointBehaviors>
        <behavior name="ServiceAspNetAjaxBehavior">
          <enableWebScript />
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
    <services>
      <service name="Service">
        <endpoint address="" behaviorConfiguration="ServiceAspNetAjaxBehavior" binding="webHttpBinding" contract="Service" />
      </service>
    </services>
</system.serviceModel>

 

4. Open the Service.cs file and add the method which will return the combobox items.

[OperationContract]
public RadComboBoxData LoadData(RadComboBoxContext context)
{
    //The RadComboBoxData object contains all required information for load on demand:
    // - the items
    // - are there more items in case of paging
    // - status message to be displayed (which is optional)
    RadComboBoxData result = new RadComboBoxData();
    NorthwindDataContext northwind = new NorthwindDataContext();

    //Get all items from the Customers table. This query will not be executed untill the ToArray method is called.
    var allCustomers = from customer in northwind.Customers
                       orderby customer.ContactName
                       select new RadComboBoxItemData
                       {
                           Text = customer.ContactName
                       };

    //In case the user typed something - filter the result set
    string text = context.Text;
    if (!String.IsNullOrEmpty(text))
    {
        allCustomers = allCustomers.Where(item => item.Text.StartsWith(text));
    }
    
    //This will execute the database query and return the data as an array of RadComboBoxItemData objects
    result.Items = allCustomers.ToArray();
            
    return result;
}

Note that the method returns an object of type RadComboBoxData. One of the properties of this class is the Items property of type array of RadComboBoxItemData objects.

    [Serializable]
    [DataContract]
    public class RadComboBoxData
    {
        public RadComboBoxData();

        [DataMember]
        public Dictionary<string, object> Context { get; set; }
        [DataMember]
        public bool EndOfItems { get; set; }
        [DataMember]
        public RadComboBoxItemData[] Items { get; set; }
        [DataMember]
        public string Message { get; set; }
        [DataMember]
        public int NumberOfItems { get; set; }
        [DataMember]
        public string Text { get; set; }
        [DataMember]
        public string Value { get; set; }
    }

We are adding the items from the database to that array.

5. Finally, add the WebService settings to the RadComboBox – just specify the Path and the Method:

<telerik:RadComboBox ID="RadComboBox1" 
    EnableLoadOnDemand="True"
    Height="150px"
    Runat="server">
    <WebServiceSettings Path="Service.svc" Method="LoadData" />            
</telerik:RadComboBox>

 

Download the sample project.

P.S. The content of this blog will be included in the online help of the respective RadControls for ASP.NET AJAX.

6 Comments

  • JVB 09 Apr
    i got the problem, the context object seems to be empty dictionary, below  is my code.
    What am I doing wrong?

     <OperationContract()> _  
        Public Function getCustomerDrivers(ByVal context As RadComboBoxContext) As RadComboBoxData  
            Dim result As RadComboBoxData  
            Dim ld As List(Of Driver) = DBHelper.getCustomersDrivers(1)  
            Dim qDrivers = From d In ld Select New RadComboBoxItemData With _  
                    {.Text = String.Concat(d.FirstName, " ", d.LastName), _  
                    .Value = d.DriverID.ToString _  
                    }  
     
     
            If context.Count > 0 AndAlso Not String.IsNullOrEmpty(context.Text) Then  
                qDriversqDrivers = qDrivers.Where(Function(x) x.Text.StartsWith(context.Text))  
            End If  
     
            Dim numberOfItems As Integer = context.NumberOfItems  
     
            Dim drivers = qDrivers.Skip(numberOfItems).Take(10)  
     
            result.Items = drivers.ToArray()  
     
            Return result  
     
        End Function 
  • Veselin Vasilev 10 Apr
    Hi JVB,

    Please try with the Q1 2009 SP1 build (version 2009.1.402.35). The context should work properly there.
  • DM 01 May
    Is there a way to customize the method signature of the WCF service to include additional parameters? We have a generic lookup service that takes in the name of a lookup table within our database and returns the code and text values to populate a combobox from that lookup table. We've got over 60 lookup tables and creating a method to return data for each one of them would be too wasteful.
  • vikas goel 15 Jun
    Hi

     Pls send the link to download version telerik:web.UI version 2009.1.402.35 dll.


    Regards
    Vikas Goel
  • E 20 Aug
    junk
  • mac 25 Jun
    Is there a way to configure this on IIS 7.5 to make it work? It works fine on my local machine but doesnt work when i deploy this to new machine that has IIS 7.5

Add comment

  1. Formatting options
       
     
     
     
     
       
  2. (optional, emails won't be shown on public pages)
  3. (optional)