ASP.NET MVC load Razor view from database

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?

Thanks.


Solution 1:

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.

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

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

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.

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

HostingEnvironment.RegisterVirtualPathProvider(new DbPathProvider());

I hope this better answers your question.