Postback null property - dynamically loaded control

I know this question has been asked many times, but I suspect that I have a unique scenario.

I load Child Control (ASCX) and set the property in this control. This works fine before postback when the property is null.

In this case, the first class loads ChildControl:

protected override void CreateChildControls() { MyUserControl control = (MyUserControl)Page.LoadControl(_ascxPath); control.MyProperty = base.MyProperty Controls.Add(control); } 

Then, in my Child Control, I have the following code:

 public partial class MyUserControl : UserControl { public MyType MyProperty { get; set; } protected void Page_Load(object sender, EventArgs e) { //Exception on next line because Property is null (only on postback) var somevalue = MyProperty.SubProperty; 
+6
source share
3 answers

Ok Let me try to explain this.
1. After creating the page you will get a full page life cycle
2. You click on some control to create a user control, and you get it
3. Now you enter the value of this control and get postback
4. On the back of the server is processed, but, as you can see, viewstate actions appear as soon as the page loads.
One of the main goals of the viewstate is to manage event management to see if they are changed, or to save their states or something else.
5. If at the time the viewstate is loaded, you are still not configured, then all its events and values ​​will be ignored.

The solution either makes it static, and simply hides it, or creates it before running actions in view mode.

+12
source

You need to add a control and set properties in the Page_Init event, otherwise you will lose the property value.

+5
source

Microsoft's explanation of the ASP.NET lifecycle page says that dynamically created controls must be created in PreInit .

It worked for me. Here is my main page:

 protected global::System.Web.UI.HtmlControls.HtmlGenericControl FiltersZone; 

(...)

  protected override void OnPreInit(EventArgs e) { base.OnPreInit(e); FiltersZone.Controls.Add(new PlanningFiltersSurgeonWeb()); } 

This dynamically created ".ascx" control contains a hidden field:

 <input id="hidTxtPaint" type="hidden" name="hidTxtPaint" runat="server" /> 

Now I can get its value from the dynamically generated ASCX control Page_Load event after " submit " or " __dopostback('hidTxtPaint') " triggered using JavaScript.

On the other hand, the value of the hidden field is always empty after POST if its main ".ascx" control is added to the main Page_Load page.

+2
source

Source: https://habr.com/ru/post/917505/


All Articles