Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load views from a Class Library project?

I tried to create a VirtualPathProvider and set the view as an embedded resource.

class AssemblyResourceVirtualFile : VirtualFile
{
    string path;

    public AssemblyResourceVirtualFile(string virtualPath)
        : base(virtualPath)
    {
        path = VirtualPathUtility.ToAppRelative(virtualPath);
    }

    public override System.IO.Stream Open()
    {
        string[] parts = path.Split('/');
        string assemblyName = parts[2];
        string resourceName = parts[3];

        assemblyName = Path.Combine(HttpRuntime.BinDirectory, assemblyName);
        var assembly = Assembly.LoadFile(assemblyName);

        if (assembly != null)
        {
            return assembly.GetManifestResourceStream(resourceName);
        }
        return null;
    }
}

And

public class AssemblyResourceProvider : System.Web.Hosting.VirtualPathProvider
{
    public AssemblyResourceProvider() { }

    private bool IsAppResourcePath(string virtualPath)
    {
        String checkPath = VirtualPathUtility.ToAppRelative(virtualPath);
        return checkPath.StartsWith("~/App_Resource/", StringComparison.InvariantCultureIgnoreCase);
    }

    public override bool FileExists(string virtualPath)
    {
        return (IsAppResourcePath(virtualPath) ||
                base.FileExists(virtualPath));
    }

    public override VirtualFile GetFile(string virtualPath)
    {
        if (IsAppResourcePath(virtualPath))
            return new AssemblyResourceVirtualFile(virtualPath);
        else
            return base.GetFile(virtualPath);
    }

    public override CacheDependency GetCacheDependency(string virtualPath,
        IEnumerable virtualPathDependencies, DateTime utcStart)
    {
        if (IsAppResourcePath(virtualPath))
            return null;
        else
            return base.GetCacheDependency(virtualPath, virtualPathDependencies, utcStart);
    }
}

My controller

return View("~/App_Resource/Blog.DLL/Blog.Views.Blog.Latest.cshtml");

It does find the view, but I end up getting this error:

... view.cshtml' must derive from WebViewPage, or WebViewPage<TModel>.

When trying to show the partial view using:

@{ Html.RenderAction("Latest", "Blog"); }

Is there a way to fix it?

Or is there an easier way to store views on a DLL?

like image 860
BrunoLM Avatar asked Mar 29 '11 02:03

BrunoLM


1 Answers

The reason this happens is because you are now serving the razor views from unknown locations the standard ~/views/web.config no longer applies. So you could put a @inherits System.Web.Mvc.WebViewPage inside your custom views but it could be quite a hassle.

You may checkout the following article.

like image 188
Darin Dimitrov Avatar answered Oct 11 '22 23:10

Darin Dimitrov