Embed code for web form

Why does this not display the date / time when rendering?

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

Is there any way to do this work?

+3
source share
6 answers

Asp.net server controls do not work with <% =, instead you can:

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

Ps. You can alternatively set the label text to code. For your script, you may need to install it on PreRenderComplete.

+4
source

I'm not sure if you have the code behind the file, but if you really need to set the label property Textin the .aspx markup, you can 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();
            base.OnPreLoad(e);
        }
    }
</script>

In this way, you can save the label control state during postback.

+3

- ...

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

Text , Page.DataBind(), -

protected override void OnPreRender(EventArgs e)
{
    if (!Page.IsPostBack)
    {
        DataBind();
    }

   base.OnPreRender(e);
}  
+1

, ,

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

asp. . <%= DateTime.Now.ToString() %>.

0

, WebControl . , , - . , , .

    <%
        var stringBuilder = new StringBuilder();
        var stringWriter = new StringWriter(stringBuilder);
        var htmlWriter = new HtmlTextWriter(stringWriter);
        var label = new Label { Text = DateTime.Now.ToString() };
        label.RenderControl(htmlWriter);
        Response.Write(stringBuilder.ToString());
     %>

, .

UPDATE:

After researching Kev’s answer, I found an even better solution. I don't have code (its MVC page), but you can still reference the control on the page through a code block, so my new solution is as follows. Note. First you need to put a block of code.

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

Thanks for inspiring Kev!

0
source

Source: https://habr.com/ru/post/1704662/


All Articles