我可以将一个Web用户控件ASCX和code背后的数据库,并从那里加载它? [英] Can I store a Web UserControl ascx and code behind in database and load it from there?
问题描述
有没有什么办法可以存储在数据库表中的用户控件的code,动态编译或从那里加载它?意味着我从数据库中的字符串,其中包含用户控件的完整code,然后将其添加到页面?
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 ?
推荐答案
几个思路:
- 使用 UserControl.LoadControl()一>与临时文件
- 使用UserControl.LoadControl()使用的HttpHandler
- 使用<一个href="http://msdn.microsoft.com/en-us/library/system.web.compilation.buildmanager.createinstancefromvirtualpath.aspx"相对=nofollow> BuildManager.CreateInstanceFromVirtualPath()(而非控制)与整个页面
- Use UserControl.LoadControl() with temp files
- Use UserControl.LoadControl() with HttpHandler
- Use BuildManager.CreateInstanceFromVirtualPath() with entire pages (instead of controls)
选项1:临时文件(最简单的)
- 为你的web应用程序写入,例如创建一个目录
〜/ tmp目录/
(并给Web应用程序的修改的&放大器; 创建的权限对该目录) -
保存用户控件的内容到一个临时文件:
- 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);
选项2:HttpHandler的
- 执行页面或HttpHandler的,通过ID获取的用户控件的内容和原始内容从数据库到
响应
流输出- 这可能无法正常工作由于UserControl.LoadControl()可能不关心响应流。
- 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.
然后加载控件中的选项1 的:
Control c = UserControl.LoadControl("~/UserControlFromDB.ascx?id=392")
- 在ASP.NET JIT缓存可能打破,因为文件名UserControlFromDB.ascx始终是相同的(仅
ID = NNN
的变化)。 URL重写可能解决此。 - 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.
方法3:编译的页面的,而不是仅仅的控件的:
Option 3: Compiling pages instead of just controls:
BuildManager.CreateInstanceFromVirtualPath()
编译一个页
在ASP.NET中的虚拟路径。所以,你可以存储整个的页的数据库和动态编译。
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.
这篇关于我可以将一个Web用户控件ASCX和code背后的数据库,并从那里加载它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!