What are and how the following statements work in Web Forms pages: <% %>, <%# %> and <%: %>

Asked

Viewed 66 times

4

I don’t know what they are or what to call them. Are they tags, statements? What are they?

In practice, I noticed some characteristics.

  1. <% %> This statement accepts executable code, but returns nothing to the web page.

  2. <%# %> This statement also accepts executable code, but appears to be limited to an expression and does not execute no-return methods. It also returns nothing to the web page.

  3. <%: %> This statement is identical to the above statement, but has its value returned to the web page.

1 answer

4


<% %>

This statement accepts executable code, but returns nothing to the web page.

It depends. Actually that’s not quite what you put.

This is the markup inherited from ASP Classic. It simply executes some imperative instruction, not necessarily writing in HTML.

Now, I can perfectly write in HTML using as follows:

<% Response.Write("Estou escrevendo no HTML!"); %>

<%# %>

This statement also accepts executable code, but appears to be limited to an expression and does not execute no-return methods. It also returns nothing to the web page.

That’s not quite it. This statement is for you to carry out data moorings (Binding) within another ASP.NET tag. For example:

<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1">
    <Columns>
        <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
        <asp:TemplateField>
            <ItemTemplate>
                <asp:Image ID="Image2" runat="server" ImageUrl='<%# Eval("Coluna")  %>' Width="70" />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

In this case, <%# Eval("Coluna") %> makes the data binding to <asp:Image>.

<%: %>

This statement is identical to the above statement, but has its value returned to the web page.

In fact <%: %> is equivalent to <%= %>, with the added character encoding suitable for HTML.

There are other notations not mentioned in the question that can be found here.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.