【问题标题】:ASP.NET control rendering HTML attributesASP.NET 控件呈现 HTML 属性
【发布时间】:2013-09-03 17:31:21
【问题描述】:

我在一个继承自 System.Web.UI.Control 的 ASP.NET Web 窗体项目中有一个自定义控件。

我想在标记中添加与该控件的属性不对应的属性,例如

<myControls:Hyperlink runat=server custom-client-side-attr="1"></<myControls:Hyperlink>

我遇到的问题是异常

类型“myControls.Hyperlink”没有名为的公共属性 '自定义客户端属性'。

我尝试过PersistChildren(false),但这并不能解决问题。自从我深入 ASP.NET Web 窗体以来已经有一段时间了,不记得这是如何完成的。

【问题讨论】:

    标签: html asp.net webforms


    【解决方案1】:

    您必须在服务器代码中添加它们:

    hl1.Attributes["custom-client-side-attr"] = "1";
    

    您仍然可以在标记中执行此操作 - 您必须在声明之前执行此操作:

    <% hl1.Attributes["custom-client-side-attr"] = "1"; %>
    <myControls:Hyperlink ID="hl1" runat=server custom-client-side-attr="1"></<myControls:Hyperlink>
    

    【讨论】:

    • 这在一种情况下对我很有用(将自定义 HTML 属性添加到由 ASP.NET RadioButtonList 输出的 table 元素)。解决方案的笨拙确实是 ASP.NET 的错我认为:为什么 ASP.NET 不简单地在标记中添加控件属性而没有相应的控件属性到控件的Attributes 集合中,这超出了我的理解;并且所讨论的问题通常也表明上游有些笨拙:当您对此无能为力时,这个“讨厌”的宝石很方便。
    • 在另一种情况下,没有骰子在标记中应用此修复:System.Web.HttpException: Untrapped Exception: The Controls collection cannot be modified because the control contains code blocks (i.e. &lt;% ... %&gt;).
    • 是的,我从来没有真正理解过那个——有时我为什么不能修改控件是没有意义的,有时当我可以修改时也没有意义。这其中的一些荒谬是为什么当 aspnet MVC 出现时我如此高兴,这样我就可以坚持使用正确的 html。
    【解决方案2】:

    如果你想要这样的属性,你必须为用户控件创建一个属性。您可以使用视图状态或隐藏控件来保持属性的持久性。您的代码可能如下所示:

    public string  custom_client_side_attr 
    {
        get {
            if (ViewState["custom_client_side_attr"] != null)
            {
                return ViewState["custom_client_side_attr"].ToString();
            }
            return string.Empty;
        }
        set
        {
            ViewState["custom_client_side_attr"] = value;
            //set custom atribute for the hyperlink here
        }
    }
    

    并通过标记访问属性:

    <myControls:Hyperlink id="myCustomControl" runat=server custom_client_side_attr="1"></<myControls:Hyperlink>
    

    或在代码中:

    myCustomControl.custom_client_side_attr="1";
    

    【讨论】:

    • 我无法添加属性,因为超链接控件是通用的。属性可以被称为任何东西
    • 如果你想访问任何属性,它必须被暴露。
    • 我不想在服务器端访问它们,我只是希望它们在客户端呈现。标准控件也有同样的想法。我只希望属性“传递”按照文档所说的那样工作
    【解决方案3】:

    如果您的自定义控件源自WebControl,它似乎可以按您的意愿工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-08
      • 2012-07-09
      • 1970-01-01
      • 1970-01-01
      • 2014-08-18
      • 1970-01-01
      • 2022-01-20
      • 2011-12-06
      相关资源
      最近更新 更多