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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4218454/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 00:35:33  来源:igfitidea点击:

ASP.NET MVC load Razor view from database

asp.net-mvcrazor

提问by pbz

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?

ScottGu 提到我们应该能够从数据库加载 Razor 视图(检查评论部分),那么有人有如何做到这一点的例子吗?

Thanks.

谢谢。

回答by Buildstarted

You might want to check Pulling a View from a database rather than a fileor Using VirtualPathProvider to load ASP.NET MVC views from DLLs

您可能想要检查从数据库而不是文件中拉取视图使用 VirtualPathProvider 从 DLL 加载 ASP.NET MVC 视图

Taking the code from my previous question on the subject.

从我之前关于该主题的问题中获取代码。

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:

FileExists()另一页的方法中,您将我在那里的测试代码替换为一些实际检查 virtualPath 是否在您的数据库中有条目的 db 代码。您的数据库将类似于:

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);
    }
}

And now we modify the DbVirtualFile

现在我们修改 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));
    }
}

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.

如果您不想,virtualPath 不必对应于真实的文件系统。您可以通过实现这两个类来覆盖功能。

You can then register your new VirtualPathProvider in the global.asax like so

然后您可以像这样在 global.asax 中注册您的新 VirtualPathProvider

HostingEnvironment.RegisterVirtualPathProvider(new DbPathProvider());

I hope this better answers your question.

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