ASP.NET:如何从JScript中访问UserControl的属性?

时间:2009-10-10 17:32:32

标签: asp.net javascript user-controls properties

我需要从<script>元素内对UserControl的用户定义属性进行读访问。当用户点击链接(我也不知道如何设置)时,需要运行此脚本。谢谢你的建议,所以!

代码隐藏:

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>

3 个答案:

答案 0 :(得分:5)

您的用户控件正在托管您的Web应用程序的服务器上执行。 js正在客户端的机器浏览器中执行。 js无法与您的用户控件进行交互。

但是,您的用户控件会在执行时发出html标记。该html包含在js可以访问的页面dom中。因此,您可以将该属性的值作为该html的一部分发出(例如,作为标记中的js变量声明)。执行此操作的最佳位置是用户控件.ascx文件。

答案 1 :(得分:5)

作为Franci wrote,您需要在服务器上构建页面时将属性的值写入html输出。

这可能是您使用示例执行此操作的最简单方法:

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

<%= %>构造只是Response.Write的缩写。)

答案 2 :(得分:1)

运行页面时,查看html源代码(右键单击查看源代码)。您会看到那里没有<asp>个标签。所有内容都转换为<html>代码。

例如:

<asp:Panel>在html中替换为<div>。如果您想访问该面板,则只能使用Javascript访问div。

同样对其他用户控件也有效。检查html等价物。看看你能做些什么。或者向我们提供html输出。

相关问题