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.
Related
What I'm doing is grabbing the HTML code for my header from a text file.
But once a User logs in I want it to say Welcome "Username" at the top, which is a dropdown to account settings, cart, etc...
So since I'm inserting the HTML into a DIV on page load, I don't actually have access to any of the elements inside in C#.
How would I go about doing this? Is there any way to access something like a (p id="name")'s inner text, after its loaded in from the text file?
Would like to do this with C# not JS please.
Edit: I have a work around for now, but I am still interested in better answers.
headerText = headerText.Replace("::Username::", Session["Username"] as string);
Here is my code for grabbing the HTML and pasting it in.
string headerText = File.ReadAllText(Server.MapPath("~/global/header.html"));
string footerText = File.ReadAllText(Server.MapPath("~/global/footer.html"));
headerText = headerText.Replace("::Username::", Session["Username"] as string);
divHeader.InnerHtml = headerText;
divFooter.InnerHtml = footerText;
To be more clear, is there anyway to access something like
<asp:Panel ID="panelAccount" runat="server">
which is stored in another HTML file.
I have done similar work in C# earlier, I use HTMLAgilityPack for doing this kind of works. Later I start using Anglesharp since it has a very good CSS selector based support.
Try anglesharp and you can modify the HTML tag like you do in jQuery.
As much as I liked Adrians response, I found out a better way to do what I needed to do, I could do with a MasterPage. I definitely be using Adrians answer for a load of other things though so it still holds valid.
Then in the C# file associated with the master page you create a property like this.
public Panel PanelAccount
{
get { return panelAccount; }
set { panelAccount = value; }
}
Then from the regular WebForm, you can call "PanelAccount" to access that property.
Here is a tutorial for how to do that.
Thanks for everyones downvotes with no inputs, you guys are stars!
I have a problem with InnerHTML property of a HtmlGenericControl object. I thought that if I assign "<b>xx</b>" to a InnerText property it will get encoded - and it does - and if I assign the same string to InnerHtml it will not get encoded - but it does!! I am confused as it goes against what I have seen here in other posts.
Background:
The string that I am assigning is loaded from database and assigned to various other strings during its lifetime and then finally replaces a placeholder with Replace method. Still it contains "<b>xx</b>" rather than encoded version... To be absolutely sure I bypassed the entire process and assigned "<b>xx</b>" string directly in code behind - the result still remains the same (i.e. encoded).
Could someone please explain why this is happening? What is it that I am doing wrong? thanks.
EDIT to make the issue 100% clear:
I need to programatically assign "<b>xx</b>" into HTMLGenericControl object and have it rendered as HTML tags and not as encoded text. What happens is I can see "<b>xx</b>" written on the screen - not desired, I want to see bold text. I thought (and it is described in documentation as such) that if I assign to InnerHtml property that the string is not encoded and displayed "as-is". It however does not behave so.
If it is feasible in your situation to replace the HTMLGenericControl with a ASP:Literal control I would do that.
I just had a similar situation come up upgrading a CMS system and that was how I handled it.
var sb = new StringBuilder();
editable.RenderControl(new HtmlTextWriter(new StringWriter(sb)));
stringDiv = sb.ToString();
Probably a simple question, but I've been browsing now for 30 mins and STILL cant find a solution!
i have a panel and it has an attribute text="something". but the panel class does not seem to have a getAttribute method... Which personally, I think is STUPID!
Code follows:
foreach (Control c in clientGrid.Controls)
{
if (c.GetType().ToString().Equals("System.Web.UI.WebControls.Panel"))
{
/*Something*/ textInsidePanel = ((Panel)c)./*Somthing*/
}
}
Now i've tried AttributeCollection text = ((Panel)c).Attributes;
and
string text = ((Panel)c).Attributes.toString();
and other useless things...
This should be really simple! when i inspect element on chrome, I can see the panel, (well the div) and i can see the text attribute right there. and i can see its value! but i want my c# code to have the value to!!
Please Help!
Alex
if I get you question right - you can use next code
asp part
<asp:Panel runat="server" ID="pnl" Text="hello world"></asp:Panel>
c# part -
string s = pnl.Attributes["Text"];
Have you tried using an accessor?:
string val = YourPanel.Attributes["Text"];
// ^ that's your attribute name
That should get the attribute's value BUT I'm pretty sure what you are doing isn't possible as attribute values are not persisted between postbacks (at least not when set via a client script). To do that you should use hidden inputs or some other form element.
The Panel control itself doesn't have a text property. But if you access the inner text as a LiteralControl it will work:
var panelContent = ((Panel)c).Controls[0] as LiteralControl;
var text = panelContent.Text;
My issue is that I have a designer that will create a custom aspx page bu without any .net controls. I need a way of adding the controls dynamically. So far the only types of controls will be textboxes and a button, but there are 30 variations of what the textboxes can be (name, phone #, email, etc). Also the textboxes may or may not need to be required. Once the textboxes are added the form will be submitted to a db.
My first thought was to have the designer place something like [name] and then replace that with a user control that has a name textbox and a required field validator. In order to determine if the validator should be enabled I was thinking that the place holder could look like this, [name;val] or [name;noval]. I could either do replace the place holders in code dynamically or set up a tool that the user pastes their html into a textbox and clicks a button which then spits out the necessary code to create the aspx page.
I'm sure there must be a better way to do this but its a fairly unique problem so I haven't been able to find any alternatives. Does anyone have any ideas?
Thanks,
Kirk
IF your designer gives you html pages, just create a new website. copy and pages all the HTML pages with the Image folders and everything to your project. then for every HTML page create an aspx page, (with the same name) copy and pages the html's tags which are between to the aspx page's and for the body copy and paste HTML page's tags which are between into the of the aspx page.
Now you have your aspx page, exactly the same as html page.
Sounds like an attempt to over-engineer a solution to what should be a non-issue.
As #Alessandro mentioned in a comment above, why can't the designer provide you with pages that have the control markup? As it stands right now, the designer isn't providing you with "a custom aspx" so much as "a custom html page." If the designer is promising ASPX but delivering only HTML, that's a misinterpretation somewhere in the business requirements.
However, even if the designer is rightfully providing only HTML, there shouldn't be a problem with that. At worst, you can set each element you need on the server to runat="server" to access them on the server-side. Or, probably better, would be to simply replace them with the ASPX control markup for the relevant controls.
Write a simple parser that will recognize the [...] tags and replace them with corresponding controls. Its pretty easy to do and i've often done this... the tag i use is usually $$(..); though, but that doesn't matter as long as your parser knows your tags.
Such a parser will consist of a simple state-machine that can be in two states; text-mode or tag-mode. Loop through the whole page-text, char for char. As long as you're in text-mode you keep appending each char into a temporary buffer. As soon as you get into tag-mode you create a LiteralControl with the content of the temporary buffer and add it to the bottom of your Control-tree, and emtpy the buffer.
Now, you still keep adding each char into the buffer, but when you hit text-mode again, you analyze the content of the buffer and create the correct control - could be a simple switch case statement. Add the control to the bottom of your control tree and keep looping through the rest of the chars unto you read the end and keep switching back and forth between text-mode and tag-mode adding LiteralControls and concrete controls.
Simple example of such a parser... written in notepad in 4 minutes, but you should get the idea.
foreach (var c in text)
{
buffer.Append(c);
if (c== '[' && mode == Text)
{
mode = Tag;
Controls.Add(new LiteralControl(buffer));
buffer.Clear();
}
if (c == ']' && mode == Tag)
{
mode = Text;
switch (buffer)
{
case "[name]": Controls.Add(new NameControl());
... the rest of possible tags
}
buffer.Clear();
}
hi guys i am using this code in my aspx page
<%for (int i=o;i<5;i++)
{%>
<asp: link button id=i text=i/>
<%}%>
at it's producing five link buttons like
i i i i i
but i just want five link buttons like that
1 2 3 4 5
with id=1,2,3,4,5 respectively
how can I can implement that
Put a placeholder in the page where you want the links:
<asp:PlaceHolder ID="LinkContainer" runat="server" />
In the Page_Load method in code behind, you put the links in the placeholder:
for (int i = 1; i <= 5; i++) {
LinkButton link = new LinkButton();
link.ID = "Link" + i.ToString();
link.Text = i.ToString();
LinkContainer.Controls.Add(link);
}
This way the controls will be created early in the page cycle, and it's possible to hook up server side events to them if you like.
(Note that I added a prefix to the id. Having an id that is only digits can cause problems in some situations.)
This isn't exactly the best way to do things in ASP.Net. Dynamic controls have many gotchas, and you just found one of them. This code is a little better (make sure the page calls DataBind() at some point):
<%for (int i=0;i<5;i++)
{%>
<asp:LinkButton id="<%# i%>" runat="server" text="<%#i%>" />
<%}%>
but you'll find that events and changes don't wire up the way you'd expect them to, if it works at all. With only five of them, it's better to just list them out by hand, and things will be much easier down the road. Or, if they came from a datasource somewhere use a repeater and create them that way.
Really, you don't want to mix code into your aspx markup at all if you can help it. Leave it for the code behind!
You need to be careful how you actually render this. Note that HTML ids that start with a number are illegal according to the specification. I would prepend some alphabetic character to the id value to be sure that it is both legal HTML and that the control id generated is legal for ASP.NET. It's unclear to me whether it's legal or not to use just a numeric value for a control id. Note that ASP.NET control id characters must be alphanumeric or an underscore.
HTML Reference:
ID and NAME tokens must begin with a
letter ([A-Za-z]) and may be followed
by any number of letters, digits
([0-9]), hyphens ("-"), underscores
("_"), colons (":"), and periods
(".").
ASP.NET Reference
Note: Only combinations of
alphanumeric characters and the
underscore character ( _ ) are valid
values for this property. Including
spaces or other invalid characters
will cause an ASP.NET page parser
error.
YOu need to actually print out the value of I on the server side.
<%for (int i=o;i<5;i++) {%>
<ASP:LinkButton Id="<%# i%>" Text="<%# i %>" />
<%}%>