CraigWardman.com

[ Data Binding to an Extension Method ]

/Blog/Post

A catalogue of my discoveries in software development and related subjects, that I think might be of use or interest to everyone else, or to me when I forget what I did!

Data Binding to an Extension Method

Wednesday, 10 December 2008


If you have defined extension methods to your entities in your BLL, (for example to format the output, or amalgamate some result) you may wish to display the return value of the extension method in a bound control, such as an ASP.NET GridView.

In order to access an extension method, you have to import the containing namespace into the codefile you are working with. The problem is that the bindings are being evaluated by the DataBinder, so even if you import the namespace using the @import directive into the page, the extension methods are only available to your code-infront code blocks, not the ASP.NET DataBinder.

In order to achieve this goal, you have 2 options.

  1. Import the namespace as above using @import and instead of using a BoundField, use a TemplateField (but don't use Eval or Bind), simply cast the Container.DataItem back to the extended type and manually add the call to the extension method.


    <%@ Import Namespace="eCommerceFramework.BLL.EntityExtensions" %>

    ---------------

    <asp:TemplateField HeaderText="Price">
    <ItemTemplate>
    <%# FormatCurrency(DirectCast(Container.DataItem, DDL.DTOs.ShopBundle).TotalPrice(),2) %>
    </ItemTemplate>
    </asp:TemplateField>



  2. Alternatively put a wrapper function in your code-behind and then call the wrapper function to get the value. You can import your extension methods in the code behind and simply return the value.


    <asp:TemplateField HeaderText="Price">
    <ItemTemplate>
    <%# FormatCurrency(GetTotalPrice(Container.DataItem),2) %>
    </ItemTemplate>
    </asp:TemplateField>

    ---------------------

    Imports eCommerceFramework.BLL.EntityExtensions

    Protected Function GetTotalPrice(ByVal b As DDL.DTOs.ShopBundle) As Decimal
    Return b.TotalPrice()
    End Function




Generally speaking, I wouldn't imagine you would be 2 way data-binding on an extension method, but if you need to make the value retreivable, put it into a runat="server" control (label/textbox) and give it an ID you can use for FindControl.

Labels: , ,

Share This!



0 Comments:

Post a Comment

<< Home

CraigWardman.com