ASP.NET server tags rendered in client HTML, not values? - asp.net

Maybe I've forgotten how to use these, but I am going crazy trying to inject a server-side value into an HTML output. There are reasons why I am doing this inline, and not server-side, so please don't suggest that as a solution.
This code on the server side:
<asp:Label ID="Label1" runat="server" Text='<%= DateTime.Now.ToString() %>' />;
Renders as this in the client HTML sent to the browser:
<span id="Label1"> <%= DateTime.Now.ToString()></span>;
And it displays as big fat empty space, and nothing output to the interface.
If I change the ASP source to using the "#" character to define as data-binding syntax, then the rendered output to browser becomes:
<span id="Label1"></span>
EDIT:
Setting Label text was just a simplified object for the sake of asking the question. In real life, I am setting the CssClass attribute, which does not allow me to use the "wrapping" workaround some have suggested. I wanted to set a public property and have all the controls update from it dynamically on page load.
Ideally, since I already have all the controls laid out on the aspx page. Just looking to add an attribute. I wanted to have:
<asp:textbox ID='MyTxtBox1' CssClass='<% strVal1 %>' />
<asp:textbox ID='MyTxtBox2' CssClass='<% strVal1 %>' />
<asp:textbox ID='MyTxtBox3' CssClass='<% strOtherVal %>' />
<asp:textbox ID='MyTxtBox4' CssClass='<% strVal1 %>' />
Now what it looks like I need to do is repeat all my (250+) controls on the codebehind in a block of code that looks like:
MyTxtBox1.CssClass=strVal1
MyTxtBox2.CssClass=strVal1
MyTxtBox4.CssClass=strVal1
MyTxtBox3.CssClass=strOtherVal

I believe that may not work on a compiled Web Application as it's not interpreted at run-time like a C# "Web Site". However, I was able to get it to work wrapping the label around the value:
<asp:Label runat="server"><%= DateTime.Now.ToString() %></asp:Label>

Set the Label1.Text = value instead of trying to use server side attrs inside of the server control

Related

ASP.NET closing tag

When I use autocompletion in VisualStudio 2010 within my .aspx application, there are different default completions at closing control tags:
<asp:CheckBox />
<asp:Label></asp:Label>
Is there a explaination for this behaviour?
<asp:CheckBox></asp:CheckBox>
<asp:Label />
Wouldn't be invalid.
This is because ASP.NET's Label control is decorated with the ParseChildrenAttribute, with ParseChildren(false) while CheckBox isn't.
You can support the same behavior whith your custom controls, for example, with the following code, Visual Studio will behave like Label if you use MyControl in the web form editor:
[ParseChildren(false)]
public class MyControl : WebControl
{
...
}
The label closing is like that
<asp:Label runat="server"></asp:Label>
because usually we type something between
<asp:Label runat="server" ID="lblOne">better start programming now</asp:Label>
that is not the case for checkbox, that we type inside of it
<asp:CheckBox runat="server" Text="enable" ID="cbOne" />
We have on both elements the Text field, why on the one we prefer to write out side... Look at this example, on Label, or On other similar controls the text that we may have to write may include characters that are not allowed inside the Text Property, maybe a complex css style or what ever... The check box from the other side is only include a small text (yes, not, something like that)
<asp:Label ID="lblLabel" runat="server">
This is a <b>"label"</b>
<br />And one more line
</asp:Label>
and more example that compiles
<asp:Label ID="lblLabel" runat="server">
This is a <b>"label"</b>
<br />And one more line
<asp:Literal runat="server" ID="ltrOneMore">One more Control Inside</asp:Literal>
</asp:Label>
---but this is not compile--
<asp:Label ID="lblLabel2" runat="server"
Text="This is a <b>"label"</b>
<br /> and one more line"
/>
At the final end is a decision that the makes make - maybe we need to ask them for the real real reason.
Now this is also not compile
<asp:CheckBox runat="server" ID="cbMyChbx">one<asp:CheckBox>
check box when is render on page is use two controls, one input and one label, so they maybe need to help user to understand that the text is not going on the input control.
<asp:CheckBox />
Because the element has no content, you can close the tag with /> instead of using a separate closing tag
<asp:Label></asp:Label> or <asp:Label />
Displays static text on a Web Forms page and allows you to manipulate it programmatically.
Learn more about it Web Server Control
All the answers above are valid, but something additional. All the asp controls are eventually rendered as HTML controls and that also defines how the asp controls behave. For e.g. it is not necessary that text in a label is always set as
<asp:Label runat="server" ID="lblOne">better start programming now</asp:Label>
it can be also done as follows
<asp:Label runat="server" ID="lblOne" Text="better start programming"></asp:Label>
now both are correct format, so it is not valid to say that any control which needs content will have a separate closing tag. It also depends on how it rendered in HTML. for e.g by default asp Label is rendered as a span and doesnt conform to XHTML standards. Hope this makes it clear, always think of how it will be rendered and ASP tries to adhere to what eventually will be rendered.
cheers

Escape HTML-entities and avoid HTML-injection in WebForm Label?

So, I thought I was a "veteran" ASP.NET WebForms developer; however, I came across this recently and was (unpleasantly) surprised that the output is not escaped:
<asp:Label Text='<%# Eval("UserData") %>' runat="server" />
Imaging where the Eval returns "<h1>joke is on you" or something more malicious to the correct rendering/security of the page.
The reason there is a Label instead of the <%# %> directly was so that, as incorrectly presumed, the contents of "UserData" would be correctly escaped for HTML. However, this apparently is not the case and the above scenario results in <h1> elements being created in the HTML markup.
Then the question can be distilled as:
Given arbitrary user input, that is to be presented as "plain text", what is an easy/reliable/secure method to insert data into the page (in a span) with correct escaping?
As per above, it should run in the context of a data-bound control. I am aware of HttpUtility.HtmlEncode, but I would like to entertain the idea of still using a control - perhaps there is a standard control for this task that I missed - to represent this case safely, without the need for wrapping the Eval. If this is misguided, based on logic or experience, it would be good to include in replies. I would not reject the notion that my use of Label in this case is entirely inappropriate.
Unfortunately, due to needing to run in a SharePoint 2010 context, I target ASP.NET for .NET 3.5, and not ASP.NET 4.
What about:
<asp:Label Text='<%#: Eval("UserData") %>' runat="server" />
This escapes the output of the eval, this only works in .NET 4.
For .NET 3.5 a solution can be:
CodeBehind:
public object EvalEncode(object container, string expression)
{
string ouput = DataBinder.Eval(container, expression).ToString();
return HttpUtility.HtmlEncode(ouput);
}
MarkUp:
<%# EvalEncode(Container.DataItem, "Text") %>
Instead of using HttpUtility.HtmlEncode, it's maybe better to use the AntiXSS library. For .NET 4 users it's already backed into the framework.
You could use an <asp:Literal ...></asp:Literal> control instead of the Label. The literal has a Mode property which you can use to tell the control to html encode its output.
Instead of this:
<asp:Label Text='<%# Eval("UserData") %>' runat="server" />
Try using:
<asp:Literal Text='<%# Eval("UserData") %>' Mode="Encode" runat="server"></asp:Literal>
Use the Microsoft Web Protection Library(Anti-XSS library) provided by microsoft for such purposes.
Security is hard, don't try to do it yourself. There is always be some hacker who is smarter.
You use it as follows:
<asp:Label Text='<%= Microsoft.Security.Application.AntiXss.HtmlEncode(Eval("UserData")) %>' runat="server" />

Outputting From Resource File

So I am working on localization for a website, and I have ran into many scenarios where I need to output the localized string from the resource, such as in the following markup:
<cc1:TabPanel HeaderText="<%= Culture.Strings.labelImageA %>">
<HeaderTemplate>
<img id="ImageA" runat="server"/>
</HeaderTemplate>
<ContentTemplate>
<uc2:Charter ID="CharterA" runat="server" />
</ContentTemplate>
</cc1:TabPanel>
In the instance above, I am attempting to output form the resource Culture.Strings.labelImageA but am receiving a warning that
This is not a scriplet.Will be output as plain text
Is there an escape character I can use in the markup in order to allow this to pull from the resource file? Otherwise, I will have to jump through many hoops to set this property in the code behind.
What surely works is to use binding markup <%# %>. This, however, would probably require calling DataBind manually on your control.
I doubt there exists a simpler way.

asp.net (4) listview gives me troubles with generating id's

i'm in a asp.net listview, in the itemtemplate.
<asp:ListView runat="server" ClientIDMode="Predictable" ClientIDRowSuffix="Texttranslations_key"ID="lvwTextitems">
This is my code in the itemtemplate:
<span runat="server" onclick="openDiv('<%= EditItemDiv.ClientID%>')" style="width: 450px;"><%# Eval("Translation")%></span>
<asp:panel runat="server" id="EditItemDiv" style="display:none">
<asp:TextBox runat="server" ID = "EditItemArea" TextMode ="MultiLine" Rows="12" Columns="50" Text="<%# Eval("Translation")%>">
</asp:TextBox>
Now i have two problems.
First the span: i want the clientID of the asp:panel in the function openDiv(), so i can create some show hide functionality.
However, i get this as result:
<span onclick="openDiv('<%= EditItemDiv.ClientID%>')" style="width: 450px;">
my code isn't seen as code, but as plain text, and i don't know why?
Second, this line gets me a runtime error (The server tag is not well formed):
<asp:TextBox runat="server" ID = "EditItemArea" TextMode ="MultiLine" Rows="12" Columns="50" Text="<%# Eval("Translation")%>">
Can somebody help me out?
ps
at first i used this code for the generation of the id's: "myid<%# Eval("Id")%>" but that didn't workout either...
ps
i'm always getting in to trouble when using the Eval and the <%# %>, so it's probably some stupid thing (i hope)
For the first part, you definitely need to be using a binding expression:
<%# EditItemDiv.ClientID %>
The <%= %> scriptlet will have no context for each item. I assume you were "paraphrasing" the syntax you say you tried, so what didn't work before?
The "server tag is not well formed" is because you are trying to use double-quotes inside double-quotes. Change the outer to single-quotes:
Text='<%# Eval("Translation")%>'>
Basically, you can't nest similar quote types. Inline script will usually demand you use double-quotes, since single-quotes have a different meaning in c#, but you can use either double or single for markup parameter quoting. The upshot is that if you need to have inline script, use single quotes to wrap the markup parameter, which frees you to use double-quotes inside it.
If you need further single quotes in the output, e.g. to render a javascript parameter, just use '. You could also use " if you wanted to render double-quotes.
OnClientClick='openDiv('EditItem(<%# Eval("something") %>');'
As stated in my comment and by jamietre to fix the binding problem you need to change the code from:
Text="<%# Eval("Translation")%>"
to
Text='<%# Eval("Translation")%>'
As for the problem with the onclick of the span, it should work as you want if you just remove the runat="server" portion. I am not sure why, but it seems that adding this causes the controls to encode the onclick property.
If you need the runat="server" on the span then I will attempt to find another solution, but there are not guarantees.

Aspx Property Interpolation

I'm a bit new to .Net development, been working in Java for some time now. I have an aspx page and we need to externalize some strings to make it more flexible.
If I have a table somewhere and there is just a string sitting outside an asp tag, I can replace it so that
<th> Specific Foo String </th>
becomes
<th> <%= Strings.foo %> </th>
and everything is fine, the problem I'm running into is how do you do this kind of interpolation on an asp tag property
I tried changing
<asp:Label runat="server" ID="lblFoo" Text="Specific Foo String Entry" />
to
<asp:Label runat="server" ID="lblFoo" Text='<%= Strings.foo %> Entry' />
and
<asp:Label runat="server" ID="lblFoo" Text='<%#Eval("Strings.foo") %> Entry' />
but neither worked. Is what I'm doing not possible in the aspx file, I know that I can simulate this by rewriting their properties in the code behind, but that's a level of overhead I'd rather not deal with.
Thanks
I think you are looking to do this:
<asp:Label runat="server" id="label1" Text='<%# Strings.Foo + " Entry"%>' />
Then in your code behind (most likely in your OnPageLoad) you need to call
if(!Page.IsPostBack) Page.DataBind();
You need to be cautious however as calling DataBind on controls like textboxes or any labels that may have changed due to logic in the code behind will have their values overwritten with the bound values. Checking that you are not on a post back can help with this, but there are still gotchas.
Also note that I had to move the " Entry" text into the binding statement. If it is placed outside the last '%>' then the binding does not work and it will spit out:
<%# Strings.foo %> Entry
In the codebehind of the page you would do this:
lblFoo.Text = Strings.foo + " Entry";
A good place to put this code would be in the overriden OnLoad method but that is simply a suggestion as I am unfamiliar with your application and the life cycle needs of your page.
If you want to do all this in the aspx page then simply do this:
<span><%= Strings.foo %> Entry</span>
as a Label renders as a span anyhow.
If your objective is an HTML table of strings, then you can create either a ListView or a GridView and DataBind to that. It would save you the trouble of writing out all of your properties and will also produce the correct table tags for the data.
Without knowing more about your data, I cannot provide a detailed code snippet.
You're talking about resources. Read Basic Instincts Resources and Localization in ASP.NET 2.0 which shows you the built in resource editor, and how to use the "<%$ ... %>"-binding, or using meta:resourceKey attribute.

Resources