More Data Binding

Last time I tried to solve one of the deficiencies of data binding by taking advantage of expando attributes. Today I want to throw an idea out there that I’ve been playing with since that blog post.I was looking at WPF’s data binding and wondered what it would take to have data binding in ASP.NET be as first class as data binding in WPF.

There is no imperative (unless you mimic the generated code) way to setup 2 way data binding in ASP.NET, but what if there was? Maybe we should be able to setup bindings in the markup as well as code.

SetBinding

This hypothetical re-design of ASP.NET data binding includes a SetBinding method on the base control class that allows users to specify bindings imperatively.

public partial class _Default : System.Web.UI.Page {

    protected void Page_Init() {           

        textBox.SetBinding("Text", new DataBinding("FirstName"));

    }

}

 

The above code would setup 2 way binding for the text property to the FirstName property in the current item being databound (if we were using some data control).

<asp:TextBox runat="server" Text="{Binding FirstName}"></asp:TextBox>

This is the equivalent markup of the code above.

Unlike the current data binding story that’s all parse time magic, all the work here would be done in the runtime. The binding syntax would just be syntactic sugar.

So we’ve re-implemented the current binding that ASP.NET supports today but what else can we do. Let’s take this concept of a binding and extend it.

Sometimes it’s useful to have control’s properties be dependant on each other. Imagine some UI where you have a pager and a drop down list of possible page sizes. Whenever the page size changes you want to update the pager’s page size so that the list updates and shows the correct number of items. This can be done today with a bunch of code but wouldn’t it be nice to have this support natively in the framework?

 

<asp:ListView ID="ProductsList" runat="server">

    <ItemTemplate>

        ...              

    </ItemTemplate>

</asp:ListView>

 

<asp:DataPager runat="server"

    PagedControlID="ProductsList"

    PageSize="{ControlBinding pageSizes, Property=SelectedValue}">

</asp:DataPager>       

 

<asp:DropDownList ID="pageSizes" runat="server">

    <asp:ListItem Text="10"></asp:ListItem>

    <asp:ListItem Text="20"></asp:ListItem>

    <asp:ListItem Text="30"></asp:ListItem>

    <asp:ListItem Text="40"></asp:ListItem>

</asp:DropDownList>

We’re using a control binding to bind the pageSizes.SelectedValue property to the pager’s PageSize property.

The prototype

Can’t have a blog post without code right :)? I’ve put together a little prototype of what this could look like but there are some gotchas.

  • There is only one bindable control in the prototype <asp:BindableTextBox> since I don’t have the power (I do but I wanted to give out a sample) to change the base Control class.
  • The binding syntax only works for text properties. The ASP parser doesn’t like it when you supply invalid values for properties. i.e  <asp:BindableTextBox TextMode=”{Binding Foo}” /> won’t work since it will complain that it can’t convert that text to a TextMode enum.

However you have full power in the code behind to do all of these things.

To use the bindable controls just add the following to the <pages> section in web.config

<add tagPrefix="asp" namespace="Web.Binding.Controls" assembly="Web.Binding"/>

What’s in the package?

There is a BindableControl base class just in case you want to write more bindable controls :).

The BindableTextBox wraps a BindableControl since C# doesn’t support multiple inheritance and we want to get the behavior of both of those classes. Ideally this would be baked into the base Control class so all of the controls get this behavior for free.

The BindableControlBuilder parses the binding expressions and generates the right binding code.

 

public class BindableControlBuilder : ControlBuilder {

    private HashSet<BindingExpression> _bindings = new HashSet<BindingExpression>();

 

    public override void Init(TemplateParser parser, ControlBuilder parentBuilder, Type type, string tagName, string id, IDictionary attribs) {

        foreach (DictionaryEntry entry in attribs.Cast<DictionaryEntry>().ToList()) {

            string key = (string)entry.Key;

            string value = entry.Value as string;

            BindingExpression expr;

            if (value != null && BindingExpression.TryParse(key, value, out expr)) {

                // Add to our list of bindings

                _bindings.Add(expr);

                // Remove the attribute so the binding expression doesn't show up as a property value

                attribs.Remove(key);

            }

        }

        base.Init(parser, parentBuilder, type, tagName, id, attribs);

    }

 

    public override void ProcessGeneratedCode(CodeCompileUnit codeCompileUnit, CodeTypeDeclaration baseType, CodeTypeDeclaration derivedType, CodeMemberMethod buildMethod, CodeMemberMethod dataBindingMethod) {

        if (buildMethod != null) {

            foreach (var binding in _bindings) {

                // Generate code foreach binding and add it to the

                // build method for this control

                var statement = binding.GenerateCode(buildMethod);

                int len = buildMethod.Statements.Count;

                buildMethod.Statements.Insert(len - 1, statement);

            }               

        }

    }

}

 

Also included in the package are 3 types of bindings:

  • Databinding – What ASP.NET has today.
  • ControlBinding – Bind a control property to another control’s property
  • ValueBinding – Bind a control property by executing a delegate to get the value.

The first 2 can be used declaratively but the ValueBinding is only supported imperatively.

I’d love to get feedback on what people think about this. You can download the prototype here.

8 Comments

  • This type of data-binding support is long overdue in ASP.NET IMHO. It would be great to see some parity with the binding model used in WPF & Silverlight, along with the simplification of the whole data-binding experience in ASP.NET Web Forms. Bring it on! :)

  • Man, oh man. I can't wait for the day when valuebinding is perfected. Excellent post - I'm gonna take a look at your bindable control. It may end up being just what I am looking for.

  • I like the look of this but i don't have much experience with wpf and was wondering if it supports the following:
    1. Allow you to specify a default value without having to use the code behind. &nbsp;Eg currently if you say
    &lt;asp:TextBox ID="txtProperty" runat="server" Text='&lt;%# Bind("Property") %&gt;' /&gt;
    and you wanted the text property to be set to 0 by default you have to set this in the code behind. &nbsp;It would also be good if this worked for the SelectedValue property of List controls even when it is databound.
    2. Allow you to do the following without having to use the code behind:
    &lt;asp:TextBox ID="txtProperty" runat="server" Text='&lt;%# Eval("Property.Property") %&gt;' /&gt;
    ObjectDataSource OnUpdating event:
    e.InputParameters.Add("DifferentProperty", ((Text)fvwDocument.FindControl("txtProperty")).Text);
    There's alot going on there but basically it is using 2 way databinding but the name of the property bound is different from the paramater name in the update method and also bound to a property from a property. &nbsp;Bind doesn't support either of these and the OnUpdating event is needed for both cases.

  • the binding for ICommand is not there. Event binding could also be describe din this post.

  • Very Nice feature ASP.Net. In which version of .net these are available sir ?

    Thanks,
    Thani

  • @MisterFantastic This isn't baked into any particular framework version of ASP.NET it was merely a prototype to show what could be done.

  • @akhi4akhil You can implement event binding as a derived binding yourself :).

  • Thank you for doing this! I tried to use Spring.NET implementation but it's not for complex scenarios.

Comments have been disabled for this content.