如何检查的ContentPlaceHolder是空的? [英] How to check if ContentPlaceHolder is empty?
问题描述
如何检查的ContentPlaceHolder绝对是空的?
How to check if ContentPlaceHolder is absolutely empty?
在的ContentPlaceHolder只有文字,没有标签和控制。
In the ContentPlaceHolder have text only, without tags and controls.
例Page.Master:
Example Page.Master:
<asp:ContentPlaceHolder runat="server" ID="Content" />
例如Test.aspx文件中:
Example Test.aspx:
<asp:Content runat="server" ContentPlaceHolderID="Content">
Custom text without controls. Content.Controls.Count is 0 and Content.HasControls is false.
</asp:Content>
我需要做的是,当占位符是空放了默认的内容是另一个控制。
What I need to do is that when the placeholder is empty put a default content is in another control.
覆盖试过两次相同的占位符,但我得到的错误,当动态负载。
Overwrite tried twice for the same placeholder but I get error when dynamic load.
推荐答案
您可以实现将呈现内容控制成一个字符串的方法,然后检查字符串找到wheahter它包含任何非空白字符:
You can implement a method that will render the content control into a string, then check the string to find wheahter it contains any non-white space chars:
private bool HasContent(Control ctrl)
{
var sb = new System.Text.StringBuilder();
using (var sw = new System.IO.StringWriter(sb))
{
using(var tw = new HtmlTextWriter(sw))
{
ctrl.RenderControl(tw);
}
}
var output = sb.ToString().Trim();
return !String.IsNullOrEmpty(output);
}
protected void Page_PreRender(object sender, EventArgs e)
{
var placeholder = Master.FindControl("FeaturedContent");
var hasContent = HasContent(placeholder);
}
这篇关于如何检查的ContentPlaceHolder是空的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!