What are the appropriate use of these two controls? From time to time I build up HTML in the code behind. Sometimes I want to output white space and I end up doing something like this.
const string twoSpaces = " ";
p.Controls.Add(new Literal { Text = twoSpaces });
or
const string twoSpaces = " ";
p.Controls.Add(new LiteralControl { Text = twoSpaces开发者_高级运维 });
My question is, is this an appropriate use of these controls? Should I be adding whitespace this way? When do I use one over the other?
I realize I could probably do something with CSS, but I really want to know what are the purposes of these two controls, and is there anything inherently wrong with using them in this fashion.
Literal uses ViewState and will remember any updates to its properties across Postbacks. LiteralControl must have its properties set on every postback.
Other than that, be very careful when using Literal. If you allow user input to be rendered in a Literal tag, you have very likely opened up a XSS attack.
Chris Pitman has answered it correctly, but I just want to add some more facts about both.
Literal is a control which can be added on both an aspx page as well as to the code behind.
asp:Literal Text="text" runat="server"
But LiteralControl cannot be added on aspx page, but only to the code behind. So that is why LiteralControl doesn't have its ViewState associated to the page class.
精彩评论