2

I went through this thread but couldn't understand much. I am very new to ASP/HTML/Server-side programming.

I tried running this code on a .aspx file:

<form id="form1" action="Default.aspx">
    <div>
        <asp:Label ID="lblName"></asp:Label>

    </div>
</form>

And I got an error when I tried to use this in the CodeFile:

protected void Page_Load(object sender, EventArgs e)
    {
        lblName.Text = "123";
    }

"lblName does not exist".

But if I use runat="server" attribute with the label, then this code works.

Also, is there any concept of nesting the runat attribute. e.g, If I specify runat=server for the form above, will all my controls inside the form automatically be configured to run at server? How does this attribute work?

In which case would I be required to specify runat=server for the and for the tag? How does the server-side know that the label is inside the form if I don't have a form object at server side? Or am I missing something?

Community
  • 1
  • 1
Hari Menon
  • 33,649
  • 14
  • 85
  • 108

2 Answers2

2

Any element marked with runat="server" lets the framework know that this will be a control on the server side. This article has more details:

ars
  • 120,335
  • 23
  • 147
  • 134
  • After reading that link, I understand why lblName won't work if I don't specify the runat attribute for that control. So runat tags are basically needed if you have to programatically modify the property of any control. Is that right? And it is not needed for static controls which you don't intend to change? – Hari Menon Jul 18 '10 at 08:43
  • Technically, RUNAT means it is not a stupid literal (string), but a control that exists at run time. All other HTML elements get compiled into long strings without any server side logic. – TomTom Jul 18 '10 at 09:00
1

Nope, there is no such nesting available in ASP.NET, you have to specify "runat" to every control that you want to use in code behind and that is part of ASP.NET web library.

Because ASP.NET can only recognize difference between client side tag (the html that runs on browser) and server side tag with help of "runat"

Akash Kava
  • 39,066
  • 20
  • 121
  • 167
  • ok.. so in which case would I be required to specify runat=server for the
    and for the
    tag? How does the server-side know that the label is inside the form if I don't have a form object at server side? Or am I missing something?
    – Hari Menon Jul 18 '10 at 08:34
  • ASP.NET has one default parent form which has runat=server by default, you do not have to use form at all in asp.net, and you dont have to use div with runat at all, you can only use runat at for controls in System.Web.HtmlControls and System.Web.WebControls. – Akash Kava Jul 18 '10 at 08:44
  • Why should asp.net CARE that the label is inside the form? It does not. – TomTom Jul 18 '10 at 09:01