HOME | SIGN UP | ACCOUNT | SUBSCRIBE | TROUBLESHOOTING | LOGIN
News · Meetings · Jobs · Downloads · Universal Thread articles · Web articles · Conference coverages · Consultants · Blogs · FAQ · User groups · Photos · Videos

Business Entities and DataBinding in ASP.Net 2.0

Jose Selesan, Independent Developer
Jose Selesan (San Nicolas de Los Arroyos, Argentina) is graduated in Computer Science and a developer especialized in .NET technologies, particularly ASP.NET. He works using Agile methodologies, especially test-driven development. He also teaches classes on .NET, Design Patterns and Development Methodologies.

Did you know that now ASP.NET supports two-way data-binding and it can also bind to business objects?

DataSource Controls

Version 2.0 of ASP.NET includes Data Source controls, a set of non-visual controls that act as a bridge between the presentation layer and the data. For instance, the SqlDataSource allows for the declarative definition of the SQL queries needed to read and update data from a web page, without the need to write anything in the code-behind.

For those of us using classes to model our application's domain entities ObjectDataSource becomes very handy. However, if we don't write our business rules tier appropriately, we may not be able to take maximum advantage of this control's features. To this purpose, we will taka a look at a way of writing our business classes to fully take advantage of the ObjectDataSource. For our example we will use the Controller Pattern. According to Craig Larman, we can implement a controller class for each business entity or for each use-case. In this case we will use a controller for each business entity.

ObjectDataSource in action

Let's assume that we have an Order class, representing a Purchase Order. Without entering into too much detail, the class would have the following definition:

public class Order
{
	public string OrderId;
	public Customer Customer;
	public Date OrderDate;
	public List Items; 
}

The Controller class for Order entities should be able to insert, update, delete or retrieve any order by its number. With these requirements we can implement the first version of the OrderController class (as an example, let's implement only the features needed to retrieve some Orders and show them in a GridView):

public class OrderController
{
	public Order GetOrder(string id)
	{ ... }
	
        public IList GetAllOrders()
	{ 
	  //calls the method on the data tier returning the orders
	}
}

The code above assumes that we already implemented a data access tier with the functionality to return the Order list from a given data source.

So we already have the needed functionality to show the orders in a GridView. To that end, we drag a GridView from the Toolbox into a WebForm. After that, beside the GridView appearing on the page, we get a dialog box helping us to quickly set the grid's DataSource. Selecting the option "New data source", Visual Studio 2005 will show a dialog box to create the data source. At this dialog we find several data source types to choose from. In our case we pick "Object" and name it "odsOrders". Then we get a wizard to finish the data source configuration.

Figure 1: Creating the DataSource

At the first step we should select the business object. In our case, let's select OrderController (if it doesn't appear on the list, uncheck "Show only data components"). At the next step we should select the methods to retrieve, insert, update and delete entities. As we will retrieve only by now, we are interested just on the first tab. It is important to remember that to be able to use method as a selection method, it should return a DataSet or a strongly-typed collection. That's why GetAllOrders returns a collection IList (so we take advantage of Framework 2.0 Generics). If we accept and execute the application, we will see our grid showing the orders.

Adding functionality

As we know, ASP.NET grid supports ordering and pagination. To implement these features in previous versions of ASP.NET we needed to hook into some events, modify several grid properties and bind it again to reflect changes. Now, by just using an ObjectDataSource this is not needed anymore, as the control does all the work for us. The ObjectDataSource has properties to indicate which parameters of the business object we can use for the current page and the ordering field.

If we look at the ObjectDataSource properties we created we will find one called SortParameterName representing the name of the parameter of the selection method on the business class receiving the field name or property to sort the data. To set a value to this property, let's edit the OrderController class:

Figure 2: Properties of ObjectDataSource

public IList GetAllOrders(string sort)
{  
  //Invokes the data tier pasing the value of the sort parameter
  //to return data ordered by this field
}

Before testing the application with sorting, we have to take a couple details in consideration. As the grid supports ascending and descending ordering, every time the ObjectDataSource executes our business object's method it sends in the parameter associated to the SortParameterName the name of the field corresponding with the column the user clicked on; but when it have to order in descending order, the value of the parameter will be formed by the name of the field followed by the word "DESC" (for instance, "OrderDate DESC"). Also, if we configure the columns manually and we change the headers' captions (HeaderText property), we have to appropriately configure the SortExpression property of each column to indicate the ordering field. If we execute the application we should be able to click any column header and -if we made everything ok- the record order should change.

Now, to enable pagination, the steps are really simple, also. First we have to set the GridView's AllowPaging property to True, and also the EnablePaging property of the DataSource. When enabling EnablePaging on the DataSource we must set also three other properties: StartRowIndexParameterName, MaximumRowsParameterName and SelectCountMethod. The method specified on SelectCountMethod will be used by the Data Source t know how many pages the grid will have (according to its PageSize), while StartRowIndexParameterName and MaximumRowsParameterName will be used to let the business class know how many records it needs for the current page and which is the first record to return. Now let's change our business class:

public IList GetAllOrders(string sort, int startRowIndex, int maximumRows)
{  
  //Invokes the data tier, passing the sort parameter
  //to return data ordered by this field
}

public int GetCount()
{
  // Returns the total reord count returned by the GetAllOrders method
}

Now we only need to give some values to the properties to related them to the code we just wrote: we assign "GetCount" to SelectCountMethod, "startRowIndex" to StartRowIndexParameterName, and "maximumRows" to MaximumRowsParameterName. Now we can execute the application again and we will find the footer under the grid showing the page numbers, and clicking them we will get the records corresponding to that page. And notice that we did all that without a single line on the page's code-behind!

Figure 3: Ordering and pagination in the grid

Contemplating all cases

It is probable that sometimes we don't need to order or paginate, so the best approach can be to overload the methods on the OrderController class to contemplate these cases. The code will look like this:

public class OrderController
{
  public IList GetAllOrders(string sort)
  {  
    // Invokes the data tier by passing the sort parameter
    // to return data ordered by this fiels
  }

  public IList GetAllOrders(string sort, int startRowIndex, int maximumRows)
  {  
    // Invokes the data tier by passing the sort parameter
    // to return data ordered by this fiels
  }
}

Conclusion

This article showed how easy is to use the ObjectDataSource to bind the presentation tier with objects in the application domain model, and we looked at the minimum requirements a business objects should comply to to take advantage of the ObjectDataSource features. Readers can try to enhance the OrderController class with the methods to update, insert and delete, and show them in the presentation tier.

More articles from this author

NoTitleDate
1.Developing Rich Web applications with AtlasOctober 2006
2.Model-View-Controller in ASP.Net with MonoRailApril 2007
3.Rich Internet Applications with SilverlightSeptember 2007
4.Unit Testing with Mock ObjectsSeptember 2006

Copyright © 1993 - 2014 Level Extreme Inc., All Rights Reserved · Telephone: 506-783-9007 Email: info@universalthread.com · Privacy & Security · Copyright · Terms & Conditions