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.
Asked
Active
Viewed 5,300 times
4 Answers
8
var webPage = htmlhelper.ViewDataContainer as WebPageBase;
var virtualPath = webPage.VirtualPath;

fredley
- 32,953
- 42
- 145
- 236

verfailliep
- 81
- 1
- 3
2
This is your best bet:

Community
- 1
- 1

Leniel Maccaferri
- 100,159
- 46
- 371
- 480
-
3thx, based on the reference I tried((RazorView)_helper.ViewContext.View).ViewPath since I am using MVC3 with Razor View. When a partial view is called from main view, I want partial view name, but the above line gives me the main view name, dont know if it is a bug in MVC3. Any help on this is appreciated. – user785153 Jun 06 '11 at 02:53
2
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

Vasiliy Shiryaev
- 21
- 3
0
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...

John Reilly
- 5,791
- 5
- 38
- 63