HTML Labels and Controls in ASP.NET Pages? - asp.net

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.

Related

Server Control or HTML control

i want to know is there any difference between server controls and HTML controls in speed?
for example you want to create a log in page that have two textbox and a button for submitting data,you can do this with both server controls and HTML controls(client_side controls(input) ),do you prefer to use server controls or HTML controls and which one is more efficiently?
which one is faster?
You always want to validate on the serverside, trusting anything from the client is a big mistake
Server Controls must be executed on the server and a Render method is called to generate the HTML. Therefore they cost a little bit of performance on the server. Depending on the control, they emit data in the ViewState as well, which costs a little bit of additional bandwidth (or very much depending on the control).
It depends on the type of control you want to use. As soon as there is any serverside processing involved (read a textbox, handle a button etc.), I always prefer the asp.net server controls, because they provide much more functionality. But if the control is just sent to the client (such as images, tables, divs etc.) I use HTML controls.
I think the server side processing doesn't take much, it takes a lot longer to get data from a database. Of course it depends on the number of users as well, whether you have to optimize or not. But I would rather use OutputCache instead of not using asp.net server controls.
Hope this helps.
The main advantage of server control is that its wrapping a control as a .Net object. It gives you a medium to access your control and its properties from code behind.
HTML controls are usually won't be accessible at client side. However, you can make them available to code behind by adding runat="server" attribute.
With the assumption that you want to access the control from code, you can chose any of them.
Now if you really want to see the difference between the asp.net control (I guess this is what you have referred to as server control) and html control, its the difference between the WebControl and HTMLControl (parents of asp.net and html controls). You basically get two different sets of wrappers. ASP.Net controls come with lot of customization and the control set is a long list than tha HTML controls list.
If we assume that you want to do some basic stuff and there is no need to access the control from code, best thing is the HTML controls, because it would save the rendering effort from the server side.
One more catch here is, if you want to utilize server side resources, such as images stored in server side, you can't access it with simple consistantly. The postback may lose the path. It would expect a control with runat="server". Its again your choice, html or asp.net controls!!!
Server controls are simple html or combination of html controls with capability to post data to server.
I would prefer server side controls for simple login screen, with preliminary client side validations.
Efficiency of controls depends on the No. of round trips it is making to the server and amount of javascript logic it is executing.

asp:image or img

Does asp:Image tag perform faster than normal HTML img tag?
I have 20 images to show on a web page (tiny images) and I have no idea which one to use.
On server-side
HTML elements in usual use (without setting runat="server" on them) are always faster compared to server-side counterparts, because they don't execute any additional server-side logic or consume other resources. They also don't add anything to page's view state.
On client-side
Simple server-side controls (those that translate to a single HTML element) are no different to normal HTML elements. But complex server-side controls (like calendar) are complex in terms of HTML element quantity thus require some additional browser resources. But making the same thing/functionality with usual HTML would create more or less similar results. So we can assume on the client-side speed is the same.
Verdict
Use server side controls only when you need to add some server-side processing to it. If not, rather use plain-old-HTML-controls. They will be processed faster on the server, will not add anything to view state and will work with the same speed on the client as their server-side counterparts.
This is true for any HTML element that has a server-side equivalent (like img that has asp:Image on the server side). When there's no client-side equivalent (like calendar) you have to of course use server side controls or use some client-side library that provides such functionality (jQuery has a date picker for instance). But you have to know Asp.net processing quite well to combine the two effectively.
use asp:image only if you have to manipulate it on the server side (dynamically setting the title, source, visible, etc).
since asp:image is "running" at the server side, it consumes a bit of memory and cpu usage.
Use an <img /> tag if you don't need to interact with it programmatically. That's less overhead (although the overhead of using asp:Image is minor).
No, there is no performance difference at all when it comes to loading the images. The asp:Image control produces an img tag, so the result that arrives to the browser is more or less identical.
The asp:Image control is convenient if you want to control it's attributes from the code behind.
The img tag will be faster for sure because no server side processing and not have ViewState (which can be disabled still).
Typically if you don't need to set properties dynamically don't use <asp:Image ... />
Remember you can always do something like:
<img src='<%= MyPathMethodInCodeBehind("some value") %>'
alt='<%= MyClass.SomeMethod(someParam) %>' />
However, the difference is really small and would argue it's not notable, yes, even for 20 images.

ASP.NET - improve performance

Is there any reason use standart HTML controls (input type=text,input type=checkbox) instead of asp.net controls ( asp:TextBox, asp:CheckBox) to improve performance?
IMHO this would be a micro optimization. You will gain performance but it won't be noticeable. On the other hand you will loose much of the flexibility offered by the server controls.
You could try to reduce the size of the ViewState by disabling it for controls that don't need it. This will reduce the size of the generated pages and improve performance.
The ASP.NET user controls will all have ViewState associated with them unless you explicitly set
EnableViewState="False"
As such, you will bloat the size of the underlying page if you have a large number of controls. As a general rule, use what meets your needs and nothing more.
Do you need to access the user control in the code-behind?
Do you need the control to maintain value across post-backs etc?
In most cases, it won't make a difference, but it is good to keep your page clean if you don't need these features.
As always with performance optimizations: it depends on the situation. Test it in your project and see if it makes any difference.
Also with .net 4.0 another con of using server controls is gone, since you can set ClientIDMode to Static, which will give you full control over ID's on your controls. Previously using just a standard textbox or button (without viewstate) would still render crazy non-readable ID's because of the way Naming Containers work. Those days are over now though :)
Remember your three options are:
use regular html which can't be referenced on the server.
add runat="server" to your existing html-tags (ie. ) and you'll be able to access it as an HtmlControl.
use the asp.net tags (<asp:* runat="server" />)
The disadvantage of option 3 is that you don't always know what the rendered html-markup will be and you have less control over it. I personally only use option 3 for more advanced controls like , the button () and third party controls. For normal html-markup that I need to reference on the server I prefer option 2.
Regarding performance I would mainly look at the rendered output, how much extra bloat is rendered to the client and such. CPU-time on the server using one or the other approach I would say is secondary compared to the different caching techniques ASP.Net has already.

WebControl vs HtmlControl. Cos and pros using them in web forms application

In web forms application, for server code, when use WebControls and when use HtmlControls? For example if I want write some text inside of span tag, should I use:
<span id="someid" runat="server"></span>
or
<asp:Label id="someid" runat="server"></asp:Label>
The main difference is that HtmlControls only provide a way of addressing a part of the page during the page cycle, whereas WebControls are stateful.
In your example, if you assign some value to the Label text, it will keep it across PostBacks.
In my experience is far better to use HtmlControls if you can, they are much more lightweight and they don't fill up your ViewState. Do use WebControls when you need them to be stateful.
For example, you might want to use a Label for a page title, because you can only assign the value once (typically in Page_OnLoad inside a if (!IsPostBack) block). You might want to use an HTML span to provide some status feedback (where the status is updated at each postback, for example).
I would use the span approach. Whatever server control you use it will finally render as an html control.
If your functionality can be done using an html control better use that..
For a server control like data grid you might have to code more to achieve those functionality by using an html table.
In that case you can use a server control.
one behaviour of asp:button is it always render as input type=submit
and asp:imagebutton always render as input type=image

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