Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 583
MadHenchbot Avatar asked Mar 23 '26 01:03

MadHenchbot


2 Answers

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.

like image 141
gilly3 Avatar answered Mar 24 '26 16:03

gilly3


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.

like image 24
MadHenchbot Avatar answered Mar 24 '26 16:03

MadHenchbot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!