Determine physical location of Razor view in MVC3

2019-06-05 17:16发布

问题:

I've created my own Razor view class, thus:

public abstract class MyWebViewPage : System.Web.Mvc.WebViewPage
{
    public MyWebViewPage() 
    {
    }
}

I use this class in my cshtml file, thus:

@inherits MyWebViewPage
<html>
    ...
</html>

I want to determine the physical location of the cshtml file in the constructor of the class, but don't seem to be able to get a handle on anything in the base class that might tell me. Any ideas?

I'm trying to work out the Area name and folder name of the view (e.g. Areas/MyArea/Views/MyViews/MyView.cshtml). The pertinent bits being "MyArea" and "MyViews".

I'm currently porting an application to use Razor views and I used to be able to do what I needed because the class name of the view was something along the lines of:

ASP_Areas_MyArea_Views_MyViews_MyView

But with Razor it's just:

ASP_MyView

回答1:

You should be able to look at the VirtualPath property. It will not be available when the constructor gets invoked, but you can override ConfigurePage and do any processing there.