2

Is there any way to get the file name (or view name) being rendered from an extension method. Something like :

public static string Something<T>(this System.Web.Mvc.HtmlHelper<T> helper, int value)
{
     string viewName = ...; // ???
     ...
     return someValueFromViewName;
}

** Edit **

The suggested question's answer :

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

does not work, and is not an answer to this question. I need the script being rendered at call time. If it is a partial, I need that partial name. Those two lines only returns the view being rendered from the controller, and not necessarily the view script being rendered at call time.

** Edit 2 **

These also ddo not work. They all return the same value; the controller's view script and not the view script (partial) calling the extension method.

var view = htmlhelper.ViewContext.View as BuildManagerCompiledView;
var virtualPath = webPage.ViewPath;
Yanick Rochon
  • 51,409
  • 25
  • 133
  • 214
  • @RaphaëlAlthaus, so it also applies to MVC4? I have search SO and I didn't find this question. – Yanick Rochon May 22 '13 at 20:09
  • Well, it's worth a try a least, from what I looked, properties used are still available... – Raphaël Althaus May 22 '13 at 20:10
  • the problem with this is that if I'm rendering a partial, I need the partial name, whereas the question you suggest only provides the controller's view script. I need the script being rendered at run-time (the calling script name) – Yanick Rochon May 22 '13 at 20:16
  • Try with: `var view = htmlhelper.ViewContext.View as BuildManagerCompiledView; var virtualPath = webPage.ViewPath;` – nemesv May 22 '13 at 21:05
  • @nemesv, same thing. It returns the controller's view, and not the calling partial script. – Yanick Rochon May 23 '13 at 03:24

2 Answers2

3

How about WebPageContext.Current.Page.VirtualPath?

public static string Something<T>(this System.Web.Mvc.HtmlHelper<T> helper, int value)
{
     string viewName = Path.GetFileName(WebPageContext.Current.Page.VirtualPath);

     string someValueFromViewName = viewName.DoSomething();
     return someValueFromViewName;
}
haim770
  • 48,394
  • 7
  • 105
  • 133
0

Since views are compiled I think that you would have to inspect the current call stack to be able to determine which partial view that is being rendered.

Getting the name of the partial view code that is calling your code is pretty much like getting the name of the method that is calling you.

Mårten Wikström
  • 11,074
  • 5
  • 47
  • 87