UI controls, such as GridView, use databinding interface to feed data. But the data may be not in the right format to show on UI for business user. That is what happened lately with a couple of my projects. For example, UI requires digit groupping, while the data to be bound has not formatted that way. The same thing happened with date values.
In implementation code, I saw data being "prepared" before being bound. Unfortunately It is not the right way to do the job. Data coming from the model should not care about formatting, while the controls which render with the data should. Because model data could be presented to different clients for different rendering.
Luckily, Asp.Net control has formatting functions. In ASP.NET 1.1 the databinding tags were:
<%# DataBinder.Eval(Container.DataItem, "expression") %>
<%# DataBinder.Eval( Container.DataItem, "expression", "format string") %>
ASP.NET 2.0 and above offer the following in addition:
<%# Eval("expression") %>
<%# Eval("expression'', "format string") %>
<%# Bind("expression") %>
<%# Bind("expression", "format string") %>
The following example customized the formatting from the control rather then "preparing" data:
<asp:TemplateField HeaderText="P&L Impact" ItemStyle-HorizontalAlign="right">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("PL_IMPACT", "{0:n}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField >
<ItemStyle width="50px" HorizontalAlign="Center" VerticalAlign="Middle" />
<ItemTemplate>
<asp:LinkButton ID="lnkExport" CommandName="Export" runat="server" CausesValidation="false"
Font-Underline="true"
CommandArgument='<%# Eval("RECORD_ID")%>' Text="Export"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
To complete, Bind and Eval are the same other than that Bind can be used for two-way binding. Two-way binding means that we can transfer data from control back to model object.
Under the hood, Data Binding is mapping between properties of a control and the data attributes. [1] has a code example of the implementation of binding.
1. http://www.devx.com/DevX/Article/35058/0/page/3
No comments:
Post a Comment