ASP.NET Maintaining ViewState for controls inside a custom control template

266 views Asked by At

I have a template property in my control declared as follows:

<TemplateContainer(GetType(GenericTemplateContainer)),
    PersistenceMode(PersistenceMode.InnerProperty),
    TemplateInstance(TemplateInstance.Single)>
Property CustomTemplate As ITemplate

In my control's Init event I have the following:

If Me.CustomTemplate IsNot Nothing Then
    Dim TemplateContainer As New GenericTemplateContainer
    Me.CustomTemplate.InstantiateIn(TemplateContainer)

    PlaceHolder.Controls.Add(TemplateContainer)
End If

This allows me to place controls in markup inside my template, but on a post back the controls inside the template are not holding their ViewState.

I have tried adding PersistChildren(True) attribute to CustomTemplate property but I cannot because it's not valid.

1

There are 1 answers

1
Harry Pehkonen On

Are you putting the values into ViewState? From what I understand, you need to do that. Either that, or re-bind with the data on every postback.

Here's what I like to do inside User Controls. I apologize for this being C# and not VB, but I don't know VB:

    public string Text {
            get { return (string)ViewState["Text"]; }
            set { ViewState["Text"] = value; }
    }

Reference: https://weblogs.asp.net/infinitiesloop/Truly-Understanding-Viewstate