Literal VS Label (ASP.NET Interview questions)
- By Shiv Prasad Koirala in ASP.NET
- Jul 15th, 2014
- 8470
- 0
Recently one of our students had gone for a ASP.NET Interview and he was asked this weird question "When should you use Literal VS Label ?". Honestly at that time I did not know the answer and I thought it's not so important either.
By default whenever I want to put a text I normally use a label as many ASP.NET developer's do.
Later in the evening when I hunted around my whole perspective to look at ASP.NET Label server control changed.
I did the following simple experiments.
Experiment 1 :-First thing I dragged a label and literal on simple form as shown below.
I ran the project and out of curiosity when I saw the HTML results I was stunned. Label was emitting out a "SPAN" tag while literal was not.
I did some more experiments further i put a bold HTML tag to see if probably there was difference in formatting.
Again the visual output was absolutely same , both where showing bold output but the label was adding an extra SPAN tag while literal was light weight.
Conclusion 1:- If you want to just display text with formatting start with a literal. Because literal controls are light weight as compared to label.
Further googling and reading things I was introduced to one more property in literal called as "Mode". This feature again made my "Conclusion 1" more stronger that always first start with a literal control to display text.
If I have HTML in my literal text and if I choose "Transform" the HTML will be parsed and displayed accordingly. But if I choose encode then the HTML will be displayed as it on the browser.
The display will be as follows, means the HTML is displayed as it is.
Now the climax when should we use "Label" server controls. After further hunting we can not apply CSS to literal , but we can apply CSS to Label. That's the whole reason why he emits those extra "SPAN" tag so that CSS can be referred.
Conclusion 2:- If you are applying CSS to your text then you have no way but use a Label.
So next time you get this googly weird ASP.NET Interview questions , below is the answer:-
"As a good practice we should always use a literal control as its lightweight and serves almost all purpose. But if we want to apply CSS to a text then we need to use the label control."
Preparing for .NET and ASP.NET Interview's start from the below video which talks about how questions are asked in .NET and ASP.NET Interviews.
Shiv Prasad Koirala
Visit us @ www.questpond.com or call us at 022-66752917... read more