ASP.NET MVC 从数据库加载 Razor 视图 [英] ASP.NET MVC load Razor view from database

查看:19
本文介绍了ASP.NET MVC 从数据库加载 Razor 视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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?

谢谢.

推荐答案

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

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

从我之前关于这个主题的问题中获取代码.

Taking the code from my previous question on the subject.

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

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.

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

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆