我创建了一个名为“ AlertBox”的UserControl,它具有属性“ AlertText”,我可以这样使用它:
<uc1:AlertBox ID="AlertBox1" runat="server" AlertText="This is an alert" />
但是,我希望能够将HTML或其他控件添加为以下子控件:
<uc1:AlertBox ID="AlertBox1" runat="server">
<p>Please click the button below to continue.</p>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Continue" />
</uc1:AlertBox>
我希望这实质上是Label控件的工作方式,您可以在其中为它的Text属性分配值或添加子内容。我查看了Label控件(https://referencesource.microsoft.com/#System.Web/UI/WebControls/Label.cs,508f83e965a6ff4b)的.NET源代码,并且看到了Text属性的以下实现:
[
Localizable(true),
Bindable(true),
WebCategory("Appearance"),
DefaultValue(""),
WebSysDescription(SR.Label_Text),
PersistenceMode(PersistenceMode.InnerDefaultProperty)
]
public virtual string Text {
get {
object o = ViewState["Text"];
return((o == null) ? String.Empty : (string)o);
}
set {
if (HasControls()) {
Controls.Clear();
}
ViewState["Text"] = value;
}
}
看起来PersistenceMode属性可能是允许我获得所需内容的关键,但是在我的代码中,我已经添加了它,并且在执行此类操作时也已添加
<uc1:AlertBox ID="AlertBox1" runat="server">
This is an alert
</uc1:AlertBox>
[DefaultValue(""), PersistenceMode(PersistenceMode.InnerDefaultProperty)]
public string AlertText
{
get
{
if (ViewState[nameof(AlertText)] == null)
ViewState[nameof(AlertText)]= "";
return (string)ViewState[nameof(AlertText)];
}
set
{
if (HasControls())
Controls.Clear();
ViewState[nameof(AlertText)] = value;
}
}
我收到以下错误:
Server Error in '/' Application.
Parser Error
Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately.
Parser Error Message: Literal content ('This is an alert') is not allowed within a 'ASP.controls_alertbox_ascx'.
Source Error:
Line 15:
Line 16: <uc1:AlertBox ID="AlertBox1" runat="server">
Line 17: This is an alert
Line 18: </uc1:AlertBox>
Line 19:
Source File: /Members/Home.aspx Line: 17
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.7.3160.0
我是否正在尝试使用WebControl(.ascx)进行操作,还是需要将其实现为UserControl?我也不想使它成为模板控件。