Search code examples
.netasp.netweb-user-controls

Can I store a Web UserControl ascx and code behind in database and load it from there?


Is there any way I can store the code of the UserControl in a database table, compile it dynamically or Load it from there ? Means I get a string from database that contains the complete code of UserControl and then add it to the page ?


Solution

  • A few ideas:

    1. Use UserControl.LoadControl() with temp files
    2. Use UserControl.LoadControl() with HttpHandler
    3. Use BuildManager.CreateInstanceFromVirtualPath() with entire pages (instead of controls)

    Option 1: temp files (easiest)

    1. Create a directory for your web application to write to, e.g. ~/tmp/ (and give the web application modify & create permissions to that directory)
    2. Save the UserControl contents to a temp file:

      string userControlContents = /* get user control contents from database */;
      string path = Server.MapPath("~/tmp/2011081612332423.ascx");
      System.IO.File.WriteAllText(path, userControlContents);
      
    3. Load the user control:

      Control c = UserControl.LoadControl("~/tmp/2011081612332423.ascx")
      
    4. Add the user control to the desired page:

      this.Controls.Add(c);
      

    Option 2: HttpHandler

    1. Implement a page or HttpHandler that gets the UserControl contents by id and outputs the raw contents from the database to the Response stream
      • This might not work since UserControl.LoadControl() probably doesn't care about the Response stream.
    2. Then load the control as in Option 1:

      Control c = UserControl.LoadControl("~/UserControlFromDB.ascx?id=392")
      
      • ASP.NET JIT caching might break since the file name "UserControlFromDB.ascx" is always the same (only id=NNN changes). URL rewriting might work around this.

    Option 3: Compiling pages instead of just controls:

    BuildManager.CreateInstanceFromVirtualPath() compiles a Page in ASP.NET from a virtual path. So you could store an entire page in the database and compile it dynamically.


    Disclaimer: I don't recommend storing controls or pages in the database; it will increase maintenance, debugging, and security costs.