Add code into server control's propery markup in Asp.Net: use CodeExpressionBuilder

Sunday, 30 August 2009 16:45 by myro

If you need to add codes through Expression Bulders, you' ll notice that are different ways to do that. Depending on what you need to write into your html rendered page, you' ll need to use different annotations. Let's see:

Write a string Resource

<asp:Button id="Btn1" runat="server" Text="<%$ appSettings: ButtonText %>" />

Call a DataBind

<%#Eval( property )%>

Write a string through Response.Write

<%= DateTime.Now %>

The problem comes out when you try to use the Response.Write method to manipulate an asp.net server control's propery. The following annotations won't work:

 <asp:Label id="lbl1" runat="server" Text="<%= DateTime.Now %>"/>

The best solution to this problem is ito implement CodeExpressionBuilder posted in InfinitiesLoop's blog. Here's a quick howto:

1- Create a class in your Web Application Project, and paste:

 [ExpressionPrefix("Code")]
public class CodeExpressionBuilder : ExpressionBuilder {
    public override CodeExpression GetCodeExpression(BoundPropertyEntry entry,
       object parsedData, ExpressionBuilderContext context) {
        return new CodeSnippetExpression(entry.Expression);
    }
}

2- Register the new Expression Builder into your Web.Config

<compilation debug="true">
  <expressionBuilders>
    <add expressionPrefix="Code" type="YOURNAMESPACE.CodeExpressionBuilder"/>
  </expressionBuilders>
</compilation>

And now you can call your code in server control's properties using the following syntax:

 <asp:Label id="lbl1" runat="server" Text="<%$ Code: DateTime.Now %>"/>

 

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Tags:   ,
Categories:   .NET
Actions:   Bookmark and Share | Permalink | Comments (2) | Comment RSSRSS comment feed