MVC3: How to get currently executing view or parti

2020-02-11 03:24发布

问题:

How to get currently executing view name or partial view name programmatically inside a HtmlHelper extension? In my situation, I can't use ViewData or can't pass view name to the extension from the View.

回答1:

var webPage = htmlhelper.ViewDataContainer as WebPageBase;
var virtualPath = webPage.VirtualPath;


回答2:

This is your best bet:

Retrieve the current view name in ASP.NET MVC?



回答3:

There is one dirty way to find real path even for partial view but it is really.. dirty.

helper.ViewDataContainer is of type like "ASP._Page_Areas_Users_Views_Customers_PersonContactsModel_cshtml". So you can parse it and get path.

Another way is a bit ugly: the base razor view class contains property VirtualPath which contains path to the view. You can pass it to helper



回答4:

Based on what Vasily said I came up with this HtmlHelper:

    public static void ReferencePartialViewBundle(this HtmlHelper helper)
    {
        // Will be something like this: "_Page_Areas_GPFund_Views_Entry__EntryVentureValuationEdit_cshtml"
        var viewDataContainerName = helper.ViewDataContainer.GetType().Name; 

        //Determine bundle name
        var bundleName = viewDataContainerName
            .Replace("__", "_¬")              //Preserve Partial "_" prefixes #1: Convert partial prefix "_" to "¬" temporarily
            .Replace("_cshtml", ".js")        //We want a js file not a cshtml
            .Replace("_", "/")
            .Replace("¬", "_")                //Preserve Partial "_" prefixes #2: Convert partial prefix "¬" back to "_" 
            .Replace("/Page/", "~/Scripts/"); //All our js files live in ~/Scripts/ and then a duplicate of the file structure for views

        //Reference bundle
        Bundles.Reference(bundleName);
    }

My purpose was to create a helper that allowed you reference a PartialView-specific Bundle using Cassette (which would have a path nearly identical to the PartialView path) but you can see the principal in action...