Click here to Skip to main content
15,867,330 members
Articles / Web Development / ASP.NET
Article

Databinding Web Forms to Objects as opposed to Datasets

Rate me:
Please Sign up or sign in to vote.
4.39/5 (10 votes)
20 May 20045 min read 77.9K   36   6
A step-by-step walkthrough describing how to bind an ASP.NET web form to an object and object collection, as opposed to binding to datatables and fields.

Screenshot

Image 1

Introduction

With the advent of ASP.NET, and Visual Studio.NET with its graphical tools to provide design-time databinding support, the concept of databinding has really come of age. Databinding to ADO.NET DataSets and DataTables is a well accepted and well documented technique. However, there is a school of thought that considers DataSets to be ugly, cumbersome and just not compatible with an object oriented approach. A discussion of this point of view is beyond the scope of this article, however, an interesting debate about this can be found here. In this article, we will simply deal with how to bind objects to web forms.

Binding Objects

Fortunately for developers who prefer to work with objects rather than DataSets, Visual Studio provides good design time support to bind controls to objects, although this approach is not particularly well documented. Databinding to objects is very similar to databinding to DataSets, except that object collections and properties are used in place of DataTables and fields. Following is a walkthrough creating a simple web project that creates a very simple Person object and binds it to a web form. The project and source code are available for download.

Model View Controller

The approach used here follows model view controller architecture. They are presented here as model, controller, view, simply because this is the logical order in which to discuss them.

Model (the business object)

I will not discuss the business object in detail as it is simply a very simple class, Person. There is nothing noteworthy about it, it exists purely to demonstrate the concept of object databinding. It contains the following properties:

Controller (PersonAdapter)

So far we have a business object (Person) and we can, of course, create a web form. But how do we get the object ‘onto’ the form so we can bind to it? One way of doing this is to create a middle tier object that can ‘hold’ our Person object and that supports databinding. For those who are familiar with 'Model View Controller' architecture, this component represents the controller in this architecture. To create a class that can both contain our object and that we can place on our web form at design-time, we create a class that inherits from System.ComponentModel.Component. I have called this class a person adapter simply because that is the convention we used in my last project.

C#
public class PersonAdapter : System.ComponentModel.Component 
{ 
 /// 
 /// provides access to our person object so a web form 
 /// can bind to the person's properties 
 /// 
 private Person person; 
 public Person Person 
 { 
   get 
  { 
    return person; 
  } 
  set 
  { 
    person=value; 
  } 
}

Presentation Code

The adapter is the logical place to put presentation code. In our example, we want to make the back color of one of our controls match the person’s favorite color. The TextBox server control has a BackColor property that can be bound to any property of type System.Drawing.Color. Thus we create this property in our PersonAdapter as:

C#
public System.Drawing.Color FavoriteColor 
{ 
  get 
  { 
    switch (person.FavoriteColor.Color) 
    { 
        case "Blue": 
          return System.Drawing.Color.Blue; 
        case "Green": 
          return System.Drawing.Color.Green; 
        case "Red": 
          return System.Drawing.Color.Red; 
        default: 
          return System.Drawing.Color.Black; 
    } 
  }
}

Design Time

Once this component is compiled, it can be placed on our toolbar in the standard manner, by right-clicking on the toolbox and selecting ‘Add/Remove Items’. Once placed on the form, the component appears in the web forms design tray:

Image 2

View (our webform)

To databind to our new PersonAdapter, we must create a new web form. Note that we can turn ‘viewstate’ off – our databinding will take care of making sure our control's text stays constant between browser refreshes.

We are now ready to bind our desired control properties. Note that ASP.NET supports binding a large number of control properties, not just text. The example form has many properties bound, we will take only one as an example. Say, we want a text box on our form with the backcolor set to the favorite color selected by the user. To do this, we select the text box we want to bind and click the ‘Databindings’ builder:

Image 3

This brings up the databindings dialog box. To bind, we simply click on the control property we want to bind, BackColor, and bind it to the Color property of the Adapter’s FavoriteColor property:

Image 4

Putting it all together

There is one final step before we can make this form ‘go’. We must tell the web form to activate databinding. This is done by calling a single method:

C#
this.DataBind()

I have added some rudimentary editing capabilities into our Person object, so the entire code in our aspx page is thus:

C#
private void Page_Load(object sender, System.EventArgs e) 
{ 
  //if the page has been posted back then apply updates requested 
  if (this.IsPostBack) 
  { 
    //pass form's Request name value collection to the 
   //static Update method 
   Person.Update(Request.Form); 
  } 

  //pass our person object to our adapter. The various controls 
  //are bound to this adapter 
  this.personAdapter1.Person=StateHelper.Person; 

  //this one line of code takes care of setting up the 
  //entire web form including setting controls' text properties 
  //back color etc etc 
  this.DataBind(); 
}

That’s literally all the client-side code required.

Conclusion

In my (biased) opinion, this is an elegant solution to many standard business data-centric web based projects that could scale to any degree of complexity. The business logic is in the business logic classes, the presentation logic is in the controllers (adapters), the web form binds to the presentation logic, and the web forms themselves don’t contain much code at all. The object oriented nature of this solution makes its code easy to read, easy to maintain, and quite flexible.

Further Development

Depending on interest levels and my time, this approach could be extended:

Whidbey

The upcoming .NET 2.0 / Visual Studio 2005 will feature ObjectSpaces, an object / relational mapping system. This will allow developers to work with ObjectSets as opposed to DataSets. ObjectSets will apparently support databinding to web controls as well. However, you may still choose to use the concept of controller objects (adapters) to abstract away the presentation logic. The point is that Microsoft is committed to providing design time tools for the object oriented programmer, so using the techniques I have outlined here will stand you in good stead for the next generation of MS products.

Two-way databinding

The data binding presented here is one way only. Data is passed from the object to the form. When the user submits the form, we just use the POSTed values to update the object. Two way databinding would pass the updated object back from the client to the server. This may be able to be achieved by the use of viewstate and/or serialization.

Add a database

Code to persist the object to a database, rather than just in memory, could be integrated. The SQL would be embedded into the business logic itself. The approximately 8 million Data Abstraction Layer methods discussed in CodeProject articles do not fit well within an object oriented architecture, I believe.

But that’s another discussion…

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
New Zealand New Zealand
Chris Lennon lives in Auckland, New Zealand. He is married with two children. He is a software development manager, currently working on a distributed Windows Forms.NET application written in C#.

He is a fan of Extreme Programming (XP) and Rapid Application Development (RAD) methedologies. His interest is in creating a template-driven approach to facilitate the production of high quality windows and web applications, within a short development cycle.

Besides looking after his kids, Chris attends Christian Life Centre Auckland, a vibrant church in the heart of Auckland City.

Comments and Discussions

 
GeneralShow Page Properties Pin
markdemich6-Dec-04 5:43
markdemich6-Dec-04 5:43 
GeneralRe: Show Page Properties Pin
Chris Lennon6-Dec-04 9:48
Chris Lennon6-Dec-04 9:48 
GeneralRe: Show Page Properties Pin
srirambalaji20-Mar-05 18:51
srirambalaji20-Mar-05 18:51 
GeneralObjectSpaces and Databinding Pin
fischetm23-May-04 2:27
fischetm23-May-04 2:27 
QuestionHow might they be used on WinForms app? Pin
Stan4th21-May-04 1:51
Stan4th21-May-04 1:51 
AnswerRe: How might they be used on WinForms app? Pin
Chris Lennon21-May-04 11:27
Chris Lennon21-May-04 11:27 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.