Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can I access HTML element without runat=server from server side?

Tags:

asp.net

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">
    protected void Page_Load(object sender, EventArgs e)
    {
        myTr.Visible = false;
        mySpan.Visible = false;
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <table runat="server">
            <tr id="myTr">
                <td>Hello</td>
                <td><span id="mySpan">World</span></td>
            </tr>
            <tr>
                <td>Hi</td>
                <td>Bye</td>
            </tr>
        </table>
    </form>
</body>
</html>

Notice myTr and mySpan both don't have runat=server, but compiler only gives error on mySpan.Visible = false.

enter image description here

Why doesn't compiler report error on myTr.Visible = false?

like image 249
Gqqnbig Avatar asked Nov 07 '22 18:11

Gqqnbig


1 Answers

My guess is that you are able to access your tr because the table runs at server and the tr is part of the table itself.

On the other way, the span element is only accessible from the client because it's not been rendered on the server side.

if you add an id to some td for the table you'll be able to access it also on the server side script. However if you remove the runat="server" from the table you'll get build errors when trying to access the table components.

<table runat="server">
    <tr id="myTr">
        <td id="myTd">Hello</td> <%--This td is also accessible from the server script--%>
        <td><span id="mySpan">World</span></td>
    </tr>
</table>

UPDATE: OK, It's not a guess anymore. According to the great explanation from Michael Amundsen and Paul Litwin on their book ASP.NET for Developers. You can see the reason there.

Summarizing here as per your comment also: On page 136, subtitle: Table Header (Th), Row (Tr) and Detail (Td) it says: You can also use server-side code to manipulate the th, tr and td tags of a table. Listing 8.9 Manipulating Th, Tr and Td Tags Using Server-Side Code is very similar to yours.

Basically a table with a runat="server" and th, tr and td elements with id attributes only (no runat="server") that are effectively accessed from the Page_Load event handler on the top of the listing.

If you continue reading you'll see the explanation about server controls and how ASP.NET matches them to Html elements.

Hope this helps!

like image 169
Karel Tamayo Avatar answered Nov 28 '22 05:11

Karel Tamayo