开发者

Serialize and Reload Dynamic Controls

开发者 https://www.devze.com 2023-03-22 16:31 出处:网络
I understand the \"why\" controls vanish on postback, and up until now I have had great success just creating what I need to do dynamically in page init.However this fell apart for me when I had to ad

I understand the "why" controls vanish on postback, and up until now I have had great success just creating what I need to do dynamically in page init. However this fell apart for me when I had to add some controls to a asp.net page based on the value of an existing dropdownlist.

So my question is simple, and I do开发者_开发知识库n't seem to be able to find a good working code example. I need to add some controls to the page based on the value of a dropdownlist. Then persist these added controls across other postbacks (session is fine).

Here is a snippet to work off of:

    protected void Page_Init(System.Object sender, System.EventArgs e)
    {
        RebuildPlaceholder();
    }

    protected void ddlGroup_Change(System.Object sender, System.EventArgs e)
    {
        ExampleDataContext ctxExample = new ExampleDataContext();
        var aryExample = (from rslt in ctxExample.mvExample
                          where rslt.label.ToLower() == ddlGroup.SelectedValue
                          select rslt);

        foreach (var objExample in aryExample)
        {
            TextBox txtCreated = new TextBox();
            txtCreated.ID = "ddl" + objExample.ID;
            plcExample.Controls.Add(txtCreated);
        }

        StorePlaceholder();
    }

    private void StorePlaceholder()
    {
        //Need code to store all controls in a placeholder.
    }

    private void RebuildPlaceholder()
    {
        //Need code to rebuild all of the controls from Session.
    }

I found this related article: Dynamically Adding Controls but I am struggling with the syntax for serializing all the controls, etc.

This can be limited to the child controls of a single placeholder that already exists on a page, just storing/restoring that placeholder's controls is what I am after.

Any version of ASP.NET is fine, if there is something that made this easy in 4.0 great.


Instead try caching the dropdown list selection. Then during the next page load use the cache to set the value selected. Then load the new controls based on that selection.

Session["CacheKey"] = DropDownList1.SelectedValue;

Then to access the Session Cache:

var value = Session["CacheKey"];

Take a look at this Microsoft article on ASP.NET Caching


I've found that DropDownList.SelectedValue is unavailable during Page.Init. But you can still get access to the value with Request[ddl.UniqueID] and then create and add all your dynamic controls.

It feels kind of like a hack, but the ASP.NET page lifecycle doesn't allow many alternatives, particularly if your controls are not serializable.

0

精彩评论

暂无评论...
验证码 换一张
取 消