asp.net-mvc – ASP.NET MVC从数据库加载Razor视图

ScottGu提到,我们应该能够到 load a Razor view from a database(查看评论部分),有没有人有这样做的例子?

谢谢。

解决方法

您可能需要检查 Pulling a View from a database rather than a fileUsing VirtualPathProvider to load ASP.NET MVC views from DLLs

从我以前的问题的代码,关于这个问题。

在另一个页面的FileExists()方法中,使用一些实际检查的数据库代码来替换测试代码,以查看virtualPath在数据库中是否有一个条目。你的数据库看起来像:

Views --tablename
    Path --view's virtual path
    SomeOtherValue

…然后你的电话会是这样的

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

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不必与真实的文件系统相对应。您可以通过实现这两个类来覆盖功能

然后,您可以在global.asax中注册新的VirtualPathProvider,如此

HostingEnvironment.RegisterVirtualPathProvider(new DbPathProvider());

我希望这个更好地回答你的问题。

相关文章

这篇文章主要讲解了“WPF如何实现带筛选功能的DataGrid”,文...
本篇内容介绍了“基于WPF如何实现3D画廊动画效果”的有关知识...
Some samples are below for ASP.Net web form controls:(fr...
问题描述: 对于未定义为 System.String 的列,唯一有效的值...
最近用到了CalendarExtender,结果不知道为什么发生了错位,...
ASP.NET 2.0 page lifecyle ASP.NET 2.0 event sequence cha...