Why do ASP.Net server control declarations require the runat="server" attribute? - asp.net

Surely the fact that they're declared beginning with "<asp:" is enough to infer they're server controls? Or is it just included for completeness (so they look similar to the server control declaration of <input runat="server" for example). Or is there some special reason?
It just always bugs me that the compiler tells me I've missed it off when I do so accidentally. Kind of like the thinking behind "var" - if the compiler knows what it is.. why bother expecting me to state it?

Taken from this forum thread:
Internet Explorer supports DHTML
behaviors.
[The asp:control syntax] does not mean server
control. You can create client DHTML
component that has namespace and will
run on the client machine. Also,
namespaces are allowed in XHTML and
techically you can use asp namespace
for something else on a client, if you
wish. Runat="server" prevents
namespace clash. If element has no
runat="server" attribute, it will be
sent to the client browser unchanged.
Therefore, you can use HTML components
(HTCs) in ASP.NET pages as well.
Have a look here
http://msdn.microsoft.com/workshop/author/behaviors/howto/creating.asp
http://msdn.microsoft.com/workshop/author/behaviors/overview.asp
Mike Schinkel also has a blog post exploring why runat=server is necessary.

Related

HTML Labels and Controls in ASP.NET Pages?

Just a general question that I've been wondering about for a while. I write a lot of pages in ASP.NET, and so all of my controls have tags beginning <asp:, and include runat="server", meaning that they're server-side controls. What I'm wondering is whether there's any advantage to using client-side controls rather than server-side controls when they don't need to be server-side.
For example, rather than having:
<asp:Label ID="lbl" runat="server" Text="This is a label" CssClass="labelclass" />
Would it be advantageous in any way (e.g. performance-wise) to instead use:
<label class="labelclass">This is a label</label>
?
Only if there is no intent to modify or access label values on the server side. It will be slightly faster to use direct HTML as in this case ASP.NET won't have to spend time to parse server control to generate anything.
If they don't need to be server-side controls, use client side controls. This will make the rendering quicker as there is less code to convert.
I generally only use server-side controls if I'm going to be referencing the control in some way in my code behind file.
On a site note, its worth mentioning, an ASP.NET Label web control renders as a <span> element, and not a <label> unless AssociatedControlId property is used.
Definitely there is a performance boost if we use client control rather than server control as server controls are parsed by asp server and it generates html for it and so it is an overhead.
Its not about how much performance but there is definitely a performance difference.
Server controls should only be used if they have to get modified on server side.
In addition to the server having to render server side controls, they also require an associated ViewState in order to be ping ponged back and forth between client and server. This results in larger requests, heavier loads, and longer load times for your pages.

Why we don't used html tag control in our asp.net pages

I am trying out with asp.net . One thing i was surprise is that in our design code we don't used general <html>,<body> etc. but we used <asp:content> , <asp:button> etc. well i tried to find it out why but ended upon the abstract msdn pages . So please help me on this one
Tags with <asp:... tag prefix means they are "server side controls", which means:
they are accessible to your program on the server side (events, parameters, etc.) and by client side script (e.g. JavaScript)
they will be "rendered" (output when running/"translated to") as standard HTML tags when you actually run your web site
As an example, while you are building your web page/s the tag <asp:textbox runat="server" id=foo... will output as <input type="text" id="foo when you run the ASP.net application in a browser.
You can create a simple web page, run it in a browser, then VIEW SOURCE to see this "translation" at work.
So while you are developing/designing your web application, ASP.Net will provide you with what they call "controls" (e.g. button controls, label controls, etc.). They will all be translated into standard HTML tags/elements at runtime.
The above relates to ASP.Net technology called "Web Forms".
You can start with it - its a bit easier to program against. When you get more advanced and/or prefer to do more "bare metal" standard HTTP POST/GET, then you can look into ASP.Net MVC/Razor - this ASP.Net architecture will let you use standard HTML and pretty much control everything (which also means you need to know how to control 'everything').
There's nothing wrong with using HTML tags in ASP.NET pages, as long as you use runat="server" on them of course. I like to use a bit of both, dependent upon what it is. I suppose a benefit of using HTML tags means that you become more comfortable with the HTML and do not depend on the ASP.NET syntax.
On the other hand, in some cases, it would be an incredibly laborious task to actually write ALL of the HTML in order to replicate a control. Something like a complex DataGrid with all the events would be an absolute nightmare to write the pure HTML/JavaScript for. Using the ASP.NET control & syntax makes it much quicker and cleaner in that scenario.

Output caching a custom control (server control)

I've come across hints about output caching a server control, but have yet to find a definitive answer to: Can the output of a server control be cached (in the same way that user controls are cached)?
The suggestions I've come across involve caching the data (not true output caching), or suggest setting the response.cache options. Ideally, I'd like to be able to drag a server control on to the page and set properties with the same names as the outputcache directive:
Example:
<cc1:MyCustomControl ID="ctl1" runat="server" CacheDuration="200" VaryByCustom="user" />
I was going to dig into the framework to see how output caching really works, but was hoping to find some information to get me started. From my limited understanding, the parser decides whether or not a page/usercontrol is cached. Since server controls are not parsed, there would be no way to stop the code from executing. I suppose I could initialize an "IsInCache" boolean and make sure that all methods check that var before executing the code. This would not entirely eliminate the server control from being executed, but it might improve performance enough by avoiding calls to the database and binding data to controls.
I'm still using .NET 3.5, and haven't had much time to explore the OutputCache provider model in .NET 4.0. Maybe there's a solution in the latest version of the framework?
Any thoughts?
I was looking for this as well and I figured I'd add the solution to this page since it came up in my web search. There is an attribute called PartialCaching that is applied to the server-side/custom control to achieve the same effect as the OutputCache directive used in ascx and aspx templates. It takes the same parameters (VaryByParameter, etc) as well. For example:
[PartialCaching(1000, "foo", null, null)]
public class ClientScriptVariableBlock : Control {
...
}
The ASP plumbing treats this the same as the template attribute, so the end result is the same. This is valuable (in my case) because I get to create common server controls outside of the web project itself that can be cached. ASCX templates don't work very well in external assemblies :)

Is it possible to modify ASP.NET to no longer require runat="server"?

I know why runat="server" is currently required (ASP.NET why runat="server"), but the consensus is that it should not be required if you incorporate a simple default into the design (I agree of course).
Would it be possible to modify, extend, decompile and recreate, intercept or otherwise change the behavior of how ASP.NET parses ASPX and ASCX files so that runat="server" would no longer be required? For instance, I assume that a version of Mono could be branched to accomplish this goal.
In case specific requirements are helpful, the following highlights one design:
During parsing, when configured namespace tags are encountered (such as "asp"), default the element's runat property to "server"
During parsing, when configured namespace tags are encountered (such as "asp"), if the element's runat property value is available, then that value should be used in place of the default
New page-level setting introduced (can be set in the page directive or web.config) that specifies the default runat value for a specific namespace tag
I'm afraid you'd have to modify the entire page parser to accomplish this, and I don't think that's possible.
On the other hand, you should be able to create your own. See the buildProviders Element and the BuildProvider class. You should be able to create your own build provider for .aspx pages and use it to replace the built-in provider.
Unfortunately, the PageBuildProvider class used by ASP.NET is internal, and the PageParser class that it uses to parse pages is sealed. You'll be entirely on your own.
Consider that runat="server" has been in ASP.NET for a decade now, and I think you'll see that this won't change anytime soon.
You'd also lose Designer support, but maybe you don't care about that.
So far as I know, there are no hooks deep enough in the ASP.NET Page handling process that would allow this. I know of no way to override or extend the parsing or processing of actual aspx/ascx code.
While ASP.NET is fairly flexible and lets your override many default behaviors (like how ViewState is saved/loaded, where Session is stored, etc) this is not one of them.
However... technically the Page object is just another HttpHandler. You could write your handler and do anything you wanted with it. All you have to do is implement everything the Page class does and then throw in this extra functionality. :) Alternately, pull out Reflector and dig through the Page object's ProcessRequest method and see where it is actually parsing/initializing the objects declared in aspx and you might get a clue how to implement the functionality you're looking for. But I suspect you'd be wasting your time.

Why does ASP.NET webforms need the Runat="Server" attribute?

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've always believed it was there more for the understanding that you can mix ASP.NET tags and HTML Tags, and HTML Tags have the option of either being runat="server" or not. It doesn't hurt anything to leave the tag in, and it causes a compiler error to take it out. The more things you imply about web language, the less easy it is for a budding programmer to come in and learn it. That's as good a reason as any to be verbose about tag attributes.
This conversation was had on Mike Schinkel's Blog between himself and Talbot Crowell of Microsoft National Services. The relevant information is below (first paragraph paraphrased due to grammatical errors in source):
[...] but the importance of <runat="server"> is more for consistency and extensibility.
If the developer has to mark some tags (viz. <asp: />) for the ASP.NET Engine to ignore, then there's also the potential issue of namespace collisions among tags and future enhancements. By requiring the <runat="server"> attribute, this is negated.
It continues:
If <runat=client> was required for all client-side tags, the parser would need to parse all tags and strip out the <runat=client> part.
He continues:
Currently,
If my guess is correct, the parser
simply ignores all text (tags or no
tags) unless it is a tag with the
runat=server attribute or a “<%”
prefix or ssi “<!– #include… (...)
Also, since ASP.NET is designed to
allow separation of the web designers
(foo.aspx) from the web developers
(foo.aspx.vb), the web designers can
use their own web designer tools to
place HTML and client-side JavaScript
without having to know about ASP.NET
specific tags or attributes.
I usually don't like to guess, but I'm going to on this one...
If you remember Microsoft's .NET marketing hype back in the day (2001?), it was hard to tell what .NET even was. Was it a server? a programming platform? a language? something new entirely? Given the ads, it was ambiguously anything you wanted it to be - it just solved any problem you might have.
So, my guess is there was a hidden grand vision that ASP.NET code could run anywhere - server side OR client side, in a copy of Internet Explorer tied to the .NET runtime. runat="server" is just a vestigial remnant, left behind because it's client-side equivalent never made it to production.
Remember those weird ads?
Related: Article from The Register with some .NET history.
Not all controls that can be included in a page must be run at the server. For example:
<INPUT type="submit" runat=server />
This is essentially the same as:
<asp:Button runat=server />
Remove the runat=server tag from the first one and you have a standard HTML button that runs in the browser. There are reasons for and against running a particular control at the server, and there is no way for ASP.NET to "assume" what you want based on the HTML markup you include. It might be possible to "infer" the runat=server for the <asp:XXX /> family of controls, but my guess is that Microsoft would consider that a hack to the markup syntax and ASP.NET engine.
Microsoft Msdn article The Forgotten Controls: HTML Server Controls explains use of runat="server" with an example on text box <input type="text"> by converting it to <input type="text" id="Textbox1" runat="server">
Doing this will give you programmatic access to the HTML element on
the server before the Web page is created and sent down to the client.
The HTML element must contain an id attribute. This attribute serves
as an identity for the element and enables you to program to elements
by their specific IDs. In addition to this attribute, the HTML element
must contain runat="server". This tells the processing server that the
tag is processed on the server and is not to be considered a
traditional HTML element.
In short, to enable programmatic access to the HTML element add runat="server" to 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.
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.
It's there because all controls in ASP .NET inherit from System.Web.UI.Control which has the "runat" attribute.
in the class System.Web.UI.HTMLControl, the attribute is not required, however, in the class System.Web.UI.WebControl the attribute is required.
edit:
let me be more specific. since asp.net is pretty much an abstract of HTML, the compiler needs some sort of directive so that it knows that specific tag needs to run server-side. if that attribute wasn't there then is wouldn't know to process it on the server first. if it isn't there it assumes it is regular markup and passes it to the client.
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.
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.
When submitting the data to ASP.NET Web server the controls mentioned as Runat = “server” will be represented as Dot Net objects in Server Application. You can manually type the code in HTML controls or else can use Run As Server option by right clicking in design view.
ASP.NET controls will automatically get this attribute once you drag it from toolbox where usually HTML controls don't.
Pretty redundant attribute, considering the "asp" tag is obviously an ASP element and should be enough to identify it as a server side accessible element.
Elsewhere however it used to elevate normal tags to be used in the code-behind.
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.
Any tag with runat=server is added as server control in Page and any html content between is handled as LiteralControls which are also added to Page controls collection.
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 use postback (except for a form "submit"). MVC relies on JQUERY to manage the page on the client side (thus bypassing the need for a lot of postback 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...

Resources