Why do I have to specify runat="server"
on all my ASP.NET controls when it is a mandatory attribute and server
is the only option available in my limited knowledge of ASP.NET, and I get an error if I don't use it?
I do understand that I can optionally use it on my HTML tags, and I do understand the client/server paradigm and what it is actually specifying.
Is it a redundant tag that could just be implied by the control being an ASP.NET control, or is there an underlying reason?
I think that Microsoft can fix this ambiguity by making the compiler add runat attribute before the page is ever compiled, something like the type-erasure thing that java has with the generics, instead of erasing, it could be writing runat=server wherever it sees asp: prefix for tags, so the developer would not need to worry about it.
My suspicion is that it has to do with how server-side controls are identified during processing. Rather than having to check every control at runtime by name to determine whether server-side processing needs to be done, it does a selection on the internal node representation by tag. The compiler checks to make sure that all controls that require server tags have them during the validation step.
If you use it on normal html tags, it means that you can programatically manipulate them in event handlers etc, eg change the href or class of an anchor tag on page load... only do that if you have to, because vanilla html tags go faster.
As far as user controls and server controls, no, they just wont work without them, without having delved into the innards of the aspx preprocessor, couldn't say exactly why, but would take a guess that for probably good reasons, they just wrote the parser that way, looking for things explicitly marked as "do something".
If @JonSkeet is around anywhere, he will probably be able to provide a much better answer.
runat="Server"
indicates a postback to the server will occur for the HTML "control."Web Forms use
postback
constantly to signal the server to process a page control event..NET
MVC
pages DO NOT usepostback
(except for a form"submit"
).MVC
relies onJQUERY
to manage the page on the client side (thus bypassing the need for a lot ofpostback
messages to the server).So:
.NET
Web Forms... use"runat"
attribute a lot in the page markup..NET
MVC
hardly ever uses"runat"
attribute in the page markup.Hope this helps clarify why
runat
is necessary...I just came to this conclusion by trial-and-error: runat="server" is needed to access the elements at run-time on server side. Remove them, recompile and watch what happens.
HTML elements in ASP.NET files are, by default, treated as text. To make these elements programmable, add a
runat="server"
attribute to the HTML element. This attribute indicates that the element should be treated as a server control.