torstai 11. maaliskuuta 2010

ASP.NET and data binding done right

I remember myself earlier having lot's of trouble with ASP.NET and databinding. Especially with events when there was post backs involved. That's because I did it all wrong. Most of people do it all wrong, even guys at Microsoft are writing terrible samples. For example at this years TechEd 2010 at Helsinki I saw many ASP.NET demos done with shortcut way.

But how to do it right? Keep the aspx-page clean. If you need to display some alternative stuff for user add it all to aspx page and then bind the visibility of those controls to your business data. From the other way around don't put presentation code to codebehind. With that I mean don't for example toggle visibility of controls from codebehind. Bind the visibilities at aspx side and let data binding do it's job.

In this post I'll give you an example how to create very simple web application with data binding done right. In the beginning you need empty ASP.NET Web Application. I named it BindingDemo.

First thing is to add properties holding your data to codebehind class.
public partial class _Default : Page
{
    protected string LabelText { get; set; }
    ...
}

Second thing is to add some controls to aspx page. Here's the ASPX-page with label, textbox and button. Nothing special there. Note the data binding of Text property of label.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="BindingDemo._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
    <head runat="server">
        <title>Binding Demo</title>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <asp:Label runat="server" Text='<%# LabelText %>' />
                <br />
                <asp:TextBox runat="server" ID="SourceText" />
                <asp:Button ID="ChangeTextButton" runat="server" 
                            Text="Change text" onclick="OnChangeText" />
            </div>
        </form>
    </body>
</html>
Third thing you need to do is to override OnDataBinding. It is called just before data binding occurs. That is the place where you get your latest data. In this example I just get stuff from session but you should propably get your data from database or something.
protected override void OnDataBinding(EventArgs e)
{
    LabelText = (string)Session[“Data”];
    base.OnDataBinding(e);
}
Last thing we want to do is to add some functionality to button. Here we are just going to store stuff to session for the sake of simplicity but in the real world you should propably store it to database.
protected void OnChangeText(object sender, EventArgs e) 
{
    Session[“Data”] = SourceText.Text;
    DataBind();
}
And that's it. Here you have very simple ASP.NET application with data binding done right. Just remember that to keep things simple you don't want to set any of controls' properties directly from code behind. Let the data binding do that always for you.

5 kommenttia:

  1. Yes, I agree. This method is also closer to the "dumb view" pattern preferred in Silverlight and ASP.NET MVC, and has additional benefits as well such as testability.

    Myself, I usually create a separate state or "presentation model" object which is bound by the UI. This allows me to separate UI state from ASP.NET event handling.

    VastaaPoista
  2. hi... your post is very much interesting and help the freshers in the development field.iPhone iPad Application Development

    VastaaPoista
  3. Thanks. This is very helpful information. I’m powerfully following along and appearing forward to learning from you.

    Hire .Net developer

    VastaaPoista
  4. I really appreciate your post which is definitely useful for me in the future.

    VastaaPoista
  5. ASP.NET is Microsoft’s platform for developing website applications. It is a high performance, productive framework for the development and delivery of database driven websites in C# or VB.NET.
    .net development sydney

    VastaaPoista