[英]ASP.Net - How do I add a HiddenField from another WebControl and maintain it?
I've got a WebControl that I want to dynamically add a HiddenField from. 我有一个WebControl,我想从中动态添加一个HiddenField。
I've tried the following example: Click here , but that doesn't work due to the fact this.Page.Form is null in the Page Init event. 我尝试了以下示例: 单击此处 ,但是由于Page Init事件中this.Page.Form为null,因此无法使用。
I've tried the following, but the value is never maintained: 我已经尝试了以下方法,但是从未保持过该值:
HiddenField hd_IsDirty = new HiddenField();
protected override void OnInit(EventArgs e)
{
this.Controls.Add(hd_IsDirty);
hd_IsDirty.ID = "hd_IsDirty";
base.OnInit(e);
}
The following works: 以下作品:
Create the control every time (seems bad!): 每次创建控件(似乎很糟糕!):
HiddenField hd_IsDirty = new HiddenField();
Tell the Page that the control requires a ControlState OnInit: 告诉页面控件需要ControlState OnInit:
this.Page.RegisterRequiresControlState(this);
Override the ControlState methods: 重写ControlState方法:
protected override object SaveControlState()
{
object obj = base.SaveControlState();
if (!string.IsNullOrEmpty(hd_IsDirty.Value))
{
if (obj != null)
{
return new Pair(obj, hd_IsDirty.Value);
}
else
{
return hd_IsDirty.Value;
}
}
else
{
return obj;
}
}
protected override void LoadControlState(object state)
{
if (state != null)
{
Pair p = state as Pair;
if (p != null)
{
base.LoadControlState(p.First);
hd_IsDirty.Value = (string)p.Second;
}
else
{
if (state is string)
{
hd_IsDirty.Value = (string)state;
}
else
{
base.LoadControlState(state);
}
}
}
}
动态控件占位符始终位于-http: //www.denisbauer.com/ASPNETControls/DynamicControlsPlaceholder.aspx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.