Is there a way to embed an expression builder within a larger string?
I'm trying to create a hyperlink where the URL includes an embedded expression. I tried writing
<asp:hyperlink id="add" runat="server" text="Add" NavigateUrl="~/admin/customer.aspx?code=<%$ AppSettings:salecode %>&action=add" />
But this didn't work -- the "<%$" and all just got included as text, no substitution was done.
Of course I could build the URL in code, it's no big deal, but I just wonder if it's possible to do this in the ASPX file somehow.
PS Just as a test, I tried putting
<asp:label id="test" runat="server" text="<%$ AppSettings:salecode %>" />
and that worked fine, so it's not that I'm mis-spelling the setting name or something dumb like that.
Try using single quotes around the NavigateUrl property:
NavigateUrl='~/admin/customer.aspx?code=<%$ AppSettings:salecode %>&action=add'
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 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" />
I have a custom ASP.NET user control implemented fully in code-behind. The control has one string property and its declarative markup looks like this:
<uc:MyControl ImageUrl="/Content/images/" runat="server" />
Most likely the actual declaration will use data binding syntax like this:
<uc:MyControl ImageUrl="<%# PageInfo.ImageUrl %>" runat="server" />
Now here's the odd part pertaining to my question. If I use the above syntax, the data binding does not work and the value of ImageUrl at run-time is the string literal of whatever is between quotes. However, if I remove the double quotes, it works as expected:
<uc:MyControl ImageUrl=<%# PageInfo.ImageUrl %> runat="server" />
The same behavior occurs with both double and single quotes. I am puzzled by this and although the code is working it's really not optimal as putting values in quotes is the norm and the approach to make the data binding work is decidedly unorthodox.
Anyone have any ideas on why this only works without quotes?
I found the problem...it was something to do with the file (probably encoding, but not sure). On a whim, I copied the code to a new file and deleted the original. Now the data binding works with the quotes as it should.
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") %>'