Monday, April 25, 2011

Inline Code on Webform Property

Why doesn't this display the date/time when rendered?

<asp:Label runat="server" ID="test" Text="<%= DateTime.Now.ToString() %>" ></asp:Label>

Is there anyway to make this work?

From stackoverflow
  • Well the asp tags are rendered. You will have to set the property at runtime. or just do the <%= DateTime.Now.ToString() %>.

  • server controls don't play well with the <%=, instead you can do:

    <span><%= DateTime.Now.ToString() %></span>

    Ps. you could alternatively set the label's text on the code-behind. It might work for your scenario to set it on the PreRenderComplete.

  • The real problem here though is I need to set the property of a WebControl with code on the markup page. The only way I've found to do this is put the whole control in a code block. Its not elegant or suggested but when all else fails this will work.

      var stringBuilder = new StringBuilder();
      var stringWriter = new StringWriter(stringBuilder);
      var htmlWriter = new HtmlTextWriter(stringWriter);
      var label = new Label { Text = DateTime.Now.ToString() };

    But this won't work if you need the control to maintain state.


    After researching Kev's answer I did find an even better solution. I don't have a code behind (its an MVC page) but you can still reference a control on the page through a code block so my new solution is the following. Note - You have to place the code block first for this to work.

        lblTest.Text = DateTime.Now.ToString();
    <asp:label runat="server" ID="lblTest" />

    Thanks for the inspiration Kev!

    eglasius : In that case, I still like better to add it on the codebehind, perhaps on the PreRenderComplete (added that comment to my answer) - or even Render (not sure if the label would grab the value, if you set it before doing base.OnRender )
    Kev : @Chief7 - you might want to add the MVC tag to the question, just a thought.
  • I'm not sure if you've got a code behind file, but if you really need to set the label's Text property in the .aspx markup you could add the following code to the page:

    <script runat="server">
        protected override void OnPreLoad(EventArgs e)
            if (!Page.IsPostBack)
                this.test.Text = DateTime.Now.ToString();

    This way you can maintain the label control's state on postback.


    chief7 : I don't have a code behind or a designer file this is an MVC view page, but thanks.
  • The simplest way to make that work would be to use a data-binding expression in place of the code render block...

    <asp:Label runat="server" ID="test" Text="<%# DateTime.Now.ToString() %>" ></asp:Label>

    Now the Text property will be set whenever Page.DataBind() is called, so in your code-behind you'll want something like

    protected override void OnPreRender(EventArgs e)
        if (!Page.IsPostBack)


Post a Comment