views:

141

answers:

1

I'm having a problem with <%= obj.ClientID %> expansion, in a .ascx user control.

I have a .js file, containing a javascript function:

function doSomething(objectId)
{
    ...
}

I have a .ascx file, with some html elements, and in one element's onclick= I want to call doSomething(), passing the ID of an element in that .ascx file, where the passed ID is of an element other than the one being clicked on, so I can't use "this.".

Maybe it'd be clearer with an example.

This works:

<script type="text/javascript">
    function redirect()
    {
        doSomething('<%= top.ClientID %>');
    }
</script>
<div id="top" runat="server">
    <img src="..." alt="..." onclick="redirect();"/>
</div>

But this does not:

<div id="top" runat="server">
    <img src="..." alt="..." onclick="doSomething('<%= top.ClientID %>');"/>
</div>

When I look at the source, I see that the <%= %> substitution has not happened, instead of "doSomething('ctl00_myControl_top');" I get "doSomething('<%= top.ClientID %>');"

For some reason, the script expansion happens in the former case, but not in the latter. The work-around, of course, is not acceptable because it will break if I include multiple copies of the control on a page - only one instance's "redirect()" function will be accessible.

Any ideas on how to make this substitution work?

+2  A: 

Works on my machine?

<div id="top" runat="server">
    <a href="#" onclick="doSomething('<%= top.ClientID %>')">rarrarara</a>
</div>

Becomes

<div id="ctl00_ContentPlaceHolder1_top">
    <a href="#" onclick="doSomething('ctl00_ContentPlaceHolder1_top')">rarrarara</a>
</div>
DaRKoN_
Same here, works on my machine as well
Jakkwylde
I'd expected it to, on my machine, which is why I was so surprised when it didn't. I thought I'd checked out all the ridiculously obvious mistakes, maybe I haven't.
Jeff Dege
Trying adding an ID and a runat="server" to your anchor. It seems that if I have a runat="server" tag on the element that has the onclick event, the <% %> expansion doesn't happen.
Jeff Dege
This is, apparently, something that Microsoft has decided not to support. Google on this error message: "Server tags cannot contain <% ... %> constructs.".The solution is to do an Attributes.Add("onclick", "") in the code-behind.
Jeff Dege
Ah, well your example didn't have a runat="server" on the img tag :)
DaRKoN_