ASP.Net DomainDataSource with Select Parameters

ASP.Net DomainDataSource with Select Parameters

ASP.Net DomainDataSource with Select Parameters

Continuing with .Net RIA Services with Silverlight and ASP.Net. In the last port I wrote about Using DomainDataSource in ASP.Net, and showed its basic usage. In this post I’ll show a more advanced scenario in which you want to use a domain service select method that takes parameters, and get the parameter value from a control on the form.

In the previous post, we had a GridView bound to a DomainDataSource that called a Select Method on the DomainService.

<asp:GridView runat="server" ID="GridView"

  AutoGenerateColumns="true"

  DataSourceID="customersDataSource">

</asp:GridView>

 

<asp:DomainDataSource runat="server" ID="customersDataSource"

  DomainServiceTypeName="Samples.Bank.Domain.BankDomainService"

  SelectMethod="GetCustomers">

</asp:DomainDataSource>

The output was:

ASP.Net DomainDataSource with Select Parameters

Now we want to filter the output list by the City property. To do that, we first have to add a method in our Domain Service that returns the data filtered by a city parameter.

public class BankDomainService : LinqToSqlDomainService<BankDataContext>

{

  public IQueryable<Customer> GetCustomers()

  {

    return this.Context.Customers;

  }

 

  public IQueryable<Customer> GetCustomersByCity(string city)

  {

    if (city == null)

      return GetCustomers();

    return GetCustomers().Where(c => c.City == city);

  }

 

  ...

}

Notice that GetCustomersByCity method uses the GetCustomers method that returns an IQueryable<Customer> and filters the result by city.

To select which city we want to filter by, lets add a ListBox with some items:

<asp:ListBox ID="lstCities" AutoPostBack="true" runat="server">

  <asp:ListItem>Tel Aviv</asp:ListItem>

  <asp:ListItem>Raanana</asp:ListItem>

  <asp:ListItem>Ramat Gan</asp:ListItem>

</asp:ListBox>

Note that I had to specify AutoPostBack=”true” in make any change to the filter, since this is a server control.

Now, in order to filter the data source according to the domain method with the select parameter I have to specify a SelectParameter that takes its value from the ListBox, and change the select method to execute.

<asp:DomainDataSource runat="server" ID="customersDataSource"
  DomainServiceTypeName="Samples.Bank.Domain.BankDomainService"

  SelectMethod="GetCustomersByCity">

  <SelectParameters>

    <asp:ControlParameter Name="city" ControlID="lstCities" PropertyName="SelectedValue" Type="String" />

  </SelectParameters >

</asp:DomainDataSource>

Now, If we run the application, we can select items in the ListBox, and the items in the GridView will be filtered by the city value.

ASP.Net DomainDataSource with Select Parameters

Enjoy!