【问题标题】:ASP.NET: How do I access a property of my UserControl, from within JScript?ASP.NET:如何从 JScript 中访问 UserControl 的属性?
【发布时间】:2009-10-10 17:32:32
【问题描述】:

我需要从 <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; }
}

平均售价:

<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>

【问题讨论】:

    标签: asp.net javascript user-controls properties


    【解决方案1】:

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

    这可能是您的示例中最简单的方法:

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

    &lt;%= %&gt;Response.Write 的缩写。)

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • “因此,您可以将属性的值作为该 html 的一部分发出” - 我该怎么做?
      【解决方案3】:

      运行页面时,查看html源代码(右键查看源代码)。你会看到那里没有&lt;asp&gt; 标签。全部转换为&lt;html&gt;标签。

      例如:

      &lt;asp:Panel&gt; 在 html 中被替换为 &lt;div&gt;。而如果要访问面板,只能用Javascript访问div。

      同样适用于其他用户控件。检查 html 等效项。看看你能做什么。或者向我们提供 html 输出。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多