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" />
Related
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
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.
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.
Accidentally I found this post about a new feature in ASP.NET 4.0: Expressions enclosed in these new brackets <%: Content %> should be rendered as HTML encoded.
I've tried this within a databound label in a FormView like so:
<asp:Label ID="MyLabel" runat="server" Text='<%: Eval("MyTextProperty") %>' />
But it doesn't work: The text property contains script tags (for testing), but the output is blank. Using the traditional way works:
<asp:Label ID="MyLabel" runat="server"
Text='<%# HttpUtility.HtmlEncode(Eval("MyTextProperty")) %>' />
What am I doing wrong?
(On a sidenote: I am too stupid to find any information: Google refuses to search for that thing. The VS2010 Online help on MSDN offers a lot of hits, but nothing related to my search. Stackoverflow search too. And I don't know how these "things" (the brackets I mean) are officially called to have a better search term.)
Any info and additional links and resources are welcome!
Thanks in advance!
You are confusing data binding expressions, which have the syntax <%#%> and are used with Eval (and Bind) with the response output tags (<%=%> and <%:%>) that cannot be used with Eval.
Use the <%#: %> HTML encoding databinding syntax. (Notice the ':' after the '#'). For example:
Text='<%#: Eval("PropertyToEval") %>'
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.