asp.net dynamically added user control saving values after postback

前端 未结 7 964
半阙折子戏
半阙折子戏 2021-01-05 10:27

Here\'s my issue. I have a usercontrol that I want to allow users to add as many instances of as necessary using a button click (each time a button is clicked, I want to ad

7条回答
  •  盖世英雄少女心
    2021-01-05 10:40

    It's an ugly solution if you have a ton of users, but you could stick the usercontrols themselves into the session. I do this with my footer control because I don't want to hit the db every time the page changes to recreate the footer.

    This solutions can get really tasking on the server if you have a lot of users and they use this feature a lot. At least I think it will...

    But you can just repopulate your placeholder that has the usercontrols in it on page_load. I can put up an example shortly.

    Example of what I do:

    if (Session["footer"] == null)
    {
     Session["footer"] = new Footer(LinksRules.BuildFooterLinks((int)WebSiteSections.Main));// where Footer is my control
    }
    footerPH.Controls.Add((Footer)Session["footer"]);
    

    Like a singleton pattern sort of...

    So as I see it you could do this on anything that will cause a postback

    Session["DynamicControls"] = PlaceHolder.Controls;

    and in the page-Load method you could:

    foreach(var control in (List)Session["DynamicControls"])
    {
      yourPlaceHolder.Controls.Add(control);
    }
    

    and if the session object is null just add a single one like they've never been there..

    I believe this will hang on to the data inside the controls like you want.

提交回复
热议问题