【问题标题】:Getting the content of an ASP.NET System.Web.UI.WebControls.PlaceHolder获取 ASP.NET System.Web.UI.WebControls.PlaceHolder 的内容
【发布时间】:2011-05-30 01:39:40
【问题描述】:

我有一个服务器控件,它有一个作为 InnerProperty 的 PlaceHolder。在渲染时的类中,我需要获取应该在 PlaceHolder 中的文本/HTML 内容。这是前端代码的示例:

<tagPrefix:TagName runat="server">
    <PlaceHolderName>
      Here is some sample text!
    </PlaceHolderName>
</tagPrefix:TagName>

这一切都很好,除了我不知道如何检索内容。我没有看到 PlaceHolder 类公开的任何渲染方法。这是服务器控件的代码。

public class TagName : CompositeControl
{
    [TemplateContainer(typeof(PlaceHolder))]
    [PersistenceMode(PersistenceMode.InnerProperty)]
    public PlaceHolder PlaceHolderName { get; set; }

    protected override void RenderContents(HtmlTextWriter writer)
    {
       // i want to retrieve the contents of the place holder here to 
       // send the output of the custom control.
    }        
}

有什么想法吗?提前致谢。

【问题讨论】:

  • 我以前从未见过有人这样做。如果它真的有效,我会感到非常惊讶。是什么让您认为“这一切都有效”?
  • 嗨,约翰,我刚刚发布了这个问题的答案。据我所知,尽管任何 Web 控件都应该能够呈现为其原始 HTML 输出,但要回答您的问题。

标签: c# asp.net controls placeholder composite-controls


【解决方案1】:

我刚刚找到了解决方案。由于我使用 PlaceHolder 对象的上下文,我没有看到渲染方法。例如,我试图将其用作值并将其分配给如下字符串:

string s = this.PlaceHolderName...

因为它位于等号的右侧,Intellisense 没有向我显示渲染方法。以下是使用 HtmlTextWriter 渲染 PlaceHolder 的方法:

   StringWriter sw = new StringWriter();
   HtmlTextWriter htw = new HtmlTextWriter(sw);
   this.PlaceHolderName.RenderControl(htw);
   string s = sw.ToString();

【讨论】:

  • 这会得到内容吗?我很惊讶。
  • 需要查看更多代码,您是在操作字符串“s”吗?否则,为什么不直接将 RenderContents 方法中的 writer 传递给 this.PlaceHodlerName.RenderControl,让内容直接进入输出流
  • s_hewitt 这仅来自演示 - 在我的实际控制中,我将 PlaceHolder 的内容输出为 XML,以便我可以应用 XSL 转换。
【解决方案2】:

将此作为第二个答案发布,以便我可以使用代码格式。这是一个使用泛型的更新方法,还使用“使用”功能自动处理文本/html 编写器。

    private static string RenderControl<T>(T c) where T : Control, new()
    {
        // get the text for the control
        using (StringWriter sw = new StringWriter())
        using (HtmlTextWriter htw = new HtmlTextWriter(sw))
        {
            c.RenderControl(htw);
            return sw.ToString();
        }
    }

【讨论】:

    猜你喜欢
    • 2015-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-25
    • 2014-11-12
    相关资源
    最近更新 更多