ASP.NET: Data Binding with ObjectDataSource
In the past when writing forms with ASP.NET I’ve usually used an SqlDataSource when binding to controls, but I’ve been doing a lot of WPF lately. Being a desktop platform, WPF has excellent support for DataBinding, but obviously since HTTP is a stateless protocol (apart from the ViewState in ASP.NET which isn’t ideal), it’s not so well suited to data binding.
One thing I’ve never really tried is binding an object to a form to display a single item (eg: a report). This leads to writing lots of tedious code like:
Order theOrder = GetOrder(orderId); litName.Text = theOrder.Name; litID.Text = theOrder.ID; litCustomer.Text = theOrder.BillingCustomer.Name; ...
It never occured to me to use an ObjectDataSource with a Repeater, just returning one row. Not only does it keep all the code in one place instead of superflous bits in the code-behind, it makes it easier to see which properties on the object are being used.
So instead of the above, you end up with:
<asp:ObjectDataSource ID="dsOrderDetails" runat="server" TypeName="DatabaseHelper" SelectMethod="GetOrder"> <SelectParameters> <asp:Parameter Name="orderId" Type="Int32" DefaultValue="-1" /> </SelectParameters> </asp:ObjectDataSource> <asp:Repeater ID="rptOrder" runat="server" DataSourceID="dsOrderDetails"> <ItemTemplate> <strong>Order ID: </strong><asp:Literal ID="lblOrderID" runat="server" Text='<%# Eval("ID") %>' /> <strong>Checkout Complete: </strong><asp:Literal ID="lblPaid" runat="server" Text='<%# Convert.ToBoolean(Eval("Paid") ?? "false") ? "Yes" : "No" %>' /> <strong>Customer Name: </strong><asp:Literal ID="lblCustomerName" runat="server" Text='<%# Eval("BillingCustomer.Name") %>' /> </div> ... <asp:GridView ID="grdItems" runat="server" DataSource='<%# Eval("Items") %>'...
Just to put those properties into context, the object might have a structure like this:
public class Order { public int ID { get; set; } public bool Paid { get; set; } public Customer BillingCustomer { get; set; } public List<OrderItem> Items { get; set; } ...


Comments
Leave a Comment