views:

491

answers:

3

I need read-access to a user-defined property of my UserControl, from within a <script> element. This script needs to run when the user clicks on the link (which I also don't know how to setup). Thanks for your advice, SO!

Code-behind:

public partial class TNLink : System.Web.UI.UserControl
{
    [System.ComponentModel.BindableAttribute(true)]
    public virtual string TNImageURL { get; set; }

    [System.ComponentModel.BindableAttribute(true)]
    public virtual string FullImageURL { get; set; }

    [System.ComponentModel.BindableAttribute(true)]
    public virtual string Caption { get; set; }
}

ASP:

<script type="text/javascript">
    //****How do I access the FullImageURL property for this line?****
    document.getElementById('imgFull').src = FullImageURL;
</script>
<div style="text-align: center">
    <a>
        <asp:Image ID="imgTN" runat="server"
            ImageUrl='<%# DataBinder.Eval (Page, "TNImageURL") %>'
            style="border: 5px solid #000000; width: 85%;" /><br />
        <asp:Label ID="lblCaption" runat="server"
            Text='<%# DataBinder.Eval (Page, "Caption") %>' />
    </a>
</div>
+4  A: 

Your user control is executing on the server that is hosting your web app. The js is executing in the client's machine browser. There's no way for the js to interact with your user control.

However, your user control does emit html markup as part of its execution. That html is included in the page dom to which the js has access. Thus, you can emit the value of the property as part of that html (for example, as a js variable declaration in a tag). The best place to do this would be the user control .ascx file.

Franci Penov
A: 

When you run the page, view the html source (right click view source). You will see that there is not <asp> tags in there. All are converted to <html> tags.

For eg:

<asp:Panel> is replaced with <div> in html. And if you want to access to the panel, you can only access to the div with Javascript.

The same is also valid for other user controls. Check the html equivalent. And see what you can. Or provide us the html output.

JCasso
+1  A: 

As Franci wrote, you need to write the value of the property to your html output while constructing the page on the server.

This is probably the easiest way to do that with your example:

<script type="text/javascript">
    document.getElementById('imgFull').src = '<%= FullImageURL %>';
</script>

(The <%= %> construct is just short for Response.Write.)

Jeff Sternal