Can I store a Web UserControl ascx and code behind in database and load it from there?
-
17-12-2020 - |
سؤال
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 ?
المحلول
A few ideas:
- Use UserControl.LoadControl() with temp files
- Use UserControl.LoadControl() with HttpHandler
- Use BuildManager.CreateInstanceFromVirtualPath() with entire pages (instead of controls)
Option 1: temp files (easiest)
- Create a directory for your web application to write to, e.g.
~/tmp/
(and give the web application modify & create permissions to that directory) 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);
Load the user control:
Control c = UserControl.LoadControl("~/tmp/2011081612332423.ascx")
Add the user control to the desired page:
this.Controls.Add(c);
Option 2: HttpHandler
- 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.
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.
- ASP.NET JIT caching might break since the file name "UserControlFromDB.ascx" is always the same (only
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.