从数据库ASP.NET MVC负荷的Razor视图 [英] ASP.NET MVC load Razor view from database
问题描述
ScottGu提到,我们应该能够从数据库加载的Razor视图(查看评论部分),所以没有任何人对如何做到这一点的例子吗?
ScottGu mentioned that we should be able to load a Razor view from a database (check the comments section), so does anybody have an example on how to do that?
感谢。
推荐答案
您可能要检查<一个href=\"http://stackoverflow.com/questions/3367106/pulling-a-view-from-a-database-rather-than-a-file\">Pulling从数据库而不是文件或<一个视图href=\"http://stackoverflow.com/questions/236972/using-virtualpathprovider-to-load-asp-net-mvc-views-from-dlls\">Using的VirtualPathProvider从DLL的
从我的previous问题服用code上的对象。
Taking the code from my previous question on the subject.
在你的 FILEEXISTS()
其他页面上更换了测试code我有一些分贝code,实际检查,看看是否有没有方法该virtualPath在你的数据库的条目。你的数据库看起来是这样的:
In your FileExists()
method on the other page you replace the test code I have there with some db code that actually checks to see if the virtualPath has an entry in your database. Your database would look something like:
Views --tablename
Path --view's virtual path
SomeOtherValue
...然后您的通话将类似于
...and your call would then be something like
public class DbPathProvider : VirtualPathProvider {
public DbPathProvider() : base() {
}
public override bool FileExists(string virtualPath) {
Database db = new Database();
return db.Views.Any(w => w.Path == virtualPath);
}
public override VirtualFile GetFile(string virtualPath) {
return new DbVirtualFile(virtualPath);
}
}
现在我们修改DbVirtualFile
And now we modify the DbVirtualFile
public class DbVirtualFile : System.Web.Hosting.VirtualFile {
public DbVirtualFile(string path) : base (path) {
}
public override System.IO.Stream Open() {
Database db = new Database();
return new System.IO.MemoryStream(
db.Views.Single(v => v.Path == this.VirtualPath));
}
}
该virtualPath不必对应一个真实的文件系统,如果你不希望它。您可以通过实现这两个类覆盖的功能。
The virtualPath doesn't have to correspond to a real filesystem if you don't want it to. You can override the functionality by implementing these two classes.
您可以再注册新的VirtualPathProvider在Global.asax像这样
You can then register your new VirtualPathProvider in the global.asax like so
HostingEnvironment.RegisterVirtualPathProvider(new DbPathProvider());
我希望这更好的回答你的问题。
I hope this better answers your question.
这篇关于从数据库ASP.NET MVC负荷的Razor视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!