Mvc3: How To Get Currently Executing View Or Partial View Programatically Inside A Htmlhelper Extension?
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 e
Solution 1:
var webPage = htmlhelper.ViewDataContainer as WebPageBase;
var virtualPath = webPage.VirtualPath;
Solution 2:
This is your best bet:
Solution 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
Solution 4:
Based on what Vasily said I came up with this HtmlHelper:
publicstaticvoidReferencePartialViewBundle(this HtmlHelper helper)
{
// Will be something like this: "_Page_Areas_GPFund_Views_Entry__EntryVentureValuationEdit_cshtml"var viewDataContainerName = helper.ViewDataContainer.GetType().Name;
//Determine bundle namevar 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...
Post a Comment for "Mvc3: How To Get Currently Executing View Or Partial View Programatically Inside A Htmlhelper Extension?"