ASPx Inline Expressing <%= %> equates at runtime to %3c%25= - c#

I have a solution with a couple of projects. Both use inline expression syntax, such as:
<p><a runat="server" href="<%=MyProject.Global.PathSite %>">My Link</a></p>
Assuming that MyProject.Global.PathSite equates to
public const String Whatever = #"http://www.myurl.com/";
At both design time and at runtime project A, the first project that I created in the solution, evaluates the expression correctly, while project B, the second project that I created a couple of months later, evaluates the expression as
%3c%25=MyProject.Global.PathSite%20%25%3e
Basically, ASP.Net treads <% %> as HTML text rather than a tag that it should process, while the second one does not.
Any thoughts?
UPDATE:
I reworked the wording of the question to better make sense.

After suffering with this issue for a couple of weeks, I finally figured out the problem.
The problem is that you cannot use <% %> in any tag, where the runat attribute is server. You can use <% %> on client side tags only.
For tags that are runat server, then simply go to the Page_Load event and enter the property through the code behind.

Try putting <%=MyProjectName.ClassName.PublicProperty %> in a literal with runar=server, you could do that with both in fact.

Related

Embedded code (<%= %>) in button control

I'm working on a project where I'm using the <%= getString("key")%> to dynamically get the appropriate text.
this works great when i use it in simple p tags, but i can't find a way to do this with controls like Button/Label etc.
Is there any way, other than calling
Mybutton.Text = getstring("key");
to dynamically add the text?
The idea is that getString retrieves af language code, and depending on that code gets a string in the appropiate language.
I've been looking around, but all i come across is using the embedded code tags directly in the aspx pages, which wont cut it for buttontext.
If you can use DataBinding instead of the <%= operator, you can use:
<asp:Button ID="MyButton" Text='<%# getstring("key") %>' />
This is a good explanation of why <%= won't work in this context.

OnClientClick event doesn't register javascript alert from code-behind

Alright, I have an embarrassingly simple question that hopefully has an embarrassingly simple answer. I am trying to get an asp:ImageButton to display an alert message that contains variables from my codebehind. Here's the overly simplified version of the code:
public string AlertMe
{
get
{
return "alert('hi');";
}
}
Now when I try and access it this way:
<asp:ImageButton ID="btn" runat="server" ImageUrl="/Images/img.ico" OnClientClick='<%=AlertMe%>'/>
I see a postback, but no alert message, as if it can't access my property at all. Meanwhile, these 2 lines:
<%=AlertMe%><br />
<a onclick="<%=AlertMe%>">click this</a>
both work fine and dandy. (The first displays the code for the javascript alert, and the second fires the alert with no issues.)
So my big question is: why does the OnClientClick event for an asp control fail to register the alert? Is there an obvious flaw I'm missing, or do I really need to register the entire event from code-behind?
You can't use the <%= ... %> syntax to set attributes of a Server Control. To set dynamic attributes on Server Controls, you have to set it in code.
this.btn.OnClientClick = this.AlertMe;
This is because <%= ... %> is a shortcut for Response.Write(). So, it isn't called until after the aspx has been parsed, evaluated, and rendering has begun. By then it's too late.
As an alternative to setting the value in the code behind, you could use this quasi-declarative technique:
<asp:ImageButton ID="btn" runat="server" ImageUrl="/Images/img.ico" />
<%
btn.OnClientClick = <%=AlertMe%>;
%>
There are other ways to get around it. This answer to a similar question discusses several approaches you can take. I can't find any "official" reference (eg, msdn) that mentions this specifically, but I didn't look that hard. Here are a couple of blog posts that discuss the issue as well:
Blog post by Jim Black: Server tags cannot contain <% ... %> constructs
Blog post at weblogs.asp.net: Use ExpressionBuilder To Avoid “Server tags cannot contain <% … %> constructs”
Or google it with bing for more fun reading.
For anyone else encountering this issue, I ran across this blog from way back when:
http://weblogs.asp.net/infinitiesloop/archive/2006/08/09/The-CodeExpressionBuilder.aspx
I found the sections about Expression Builders and ViewState concerns to be particularly informative.
I think its a quoting problem. Try
OnClientClick="<%=AlertMe%>"

Why does this line of localization behave this way?

I'm localizing an ASP.NET web site. Usually to localize text in an .aspx page I just use
<%= Resources.ResourceFile.ResourceName %>
For asp.net controls, this won't work. I have to use the syntax
<%$ Resources:ResourceFile, ResourceName %>
However, if I have a button and localize the Text property that way, but add any additional characters after it, the localization breaks and it shows as plaintext.
So Text="<%$ Resources:ResourceFile, ResourceName %> »" displays as
<%$ Resources:ResourceFile, ResourceName %> »
I'm sure there is a valid reason for this, I just can't find the explanation on MSDN on how the Text property evaluates this. I'm not even 100% sure on what the <%$ actually does.
What's happening is that ASP.net is invoking an Expression Builder. What effectively happens here is that rather than the ASP.net compiler translating your:
<asp:AControlWithATextProperty runat="server" Text="Some Text">
to:
AControlWithATextProperty ctl1 = new AControlWithATextProperty();
ctl1.Text = "Some Text";
When it transforms the markup in the .aspx file into a .cs file combined with the code-behind, it actually does something similar to this:
<asp:AControlWithATextProperty runat="server" Text="<%$ Resources:ResourceFile, ResourceName %>">
Becomes:
AControlWithATextProperty ctl1 = new AControlWithATextProperty();
ctl1.Text = ResourceExpressionBuilder.EvaluateExpression("ResourceFile, Resourcename");
It would seem that the asp.net compiler can't handle concatenating the content of the <%$ %> tags with any further text in the property from markup. Either a bug, or by design. i.e. You don't end up with ctl1.Text = ResourceExpressionBuilder.EvaluateExpression("ResourceFile, Resourcename") + "»".
You can read more about the ResourceExpressionBuilder on msdn, ExpressionBuilder in general, or if you really want to; an implementation of one for localisation (database backed, hence the fact that I didn't use the ResourceExpressionBuilder) on my blog (3 parts).

Beginner question: Can I put an "if" statement between two <% %> tags in ASP.Net?

This is a real newbie question, I hope you can forgive me. I was wondering, can I put an if statement between two <% %> directly in an .aspx document? If so, how...?
The specific problem I'm having is this: I want to put the user's HTTP Referrer as a parameter in a link they click on (this must sound terribly counter-intuitive, but I have my reasons for doing it this way!).
So my problem is that sometimes Request.UrlReferrer returns a null value. To counter this, I was hoping to put something like:
<%# if(Request.UrlReferrer != null) { Server.UrlEncode(Request.UrlReferrer.ToString()) } %>
But it's not working... ("Error: Invalid expression term 'if'").
Thanks for any help!
You can do:
<% if(Request.UrlReferrer != null) { %><%=Server.UrlEncode(Request.UrlReferrer.ToString())%><% } %>
or
<%=Request.UrlReferrer == null ? "" : Server.UrlEncode(Request.UrlReferrer.ToString()) %>
any c# or vb .net code can be nested inside <% %> tags. in fact, if you create your pages in visual studio without code behind. you can write the entire code in these tags within the html

Using delegates to render html blocks in asp.net

I thought of a neat hack this morning, probably not original, but I haven't seen it before. I don't consider it good practice, but can help when you need to render a block of code repeatedly around your page, and don't want to touch other code or create other files (partial views or components).
In your .aspx file create an anonymous delegate like so:
<%
Action<DataType> renderMe = data => {
%> Some html text That can contain quotes, etc.
And other <%= data.something %> stuff...
<%
};
%>
Then you can simply use it anywhere you want: (myvar1 and myvar2 are of type DataType)
This is some html and I want the block here: <% renderMe(myvar1); %> ...
or maybe here <% renderMe(myvar2); %>
I know it's not a great idea, but can anyone see any problems with doing this?
This ain't bad per se. Quite similar to Spark's macros (that looks better imho). Rashud`s script manager (for advanced js initialization) uses the same technique. MvcContrib's grid renderer does the same too.
Thing is - niche when this is suitable is really narrow. Only when desired snippet of html should be passed to server side or when you want to re-use it twice or more in context of one specific view but don't want to create separate partial view.

Categories

Resources