1

I'm trying to create a HtmlExtension to retrieve the name of the current view.

However, I don't want to have the requested view (e.g. "LogOn" for "/Account/LogOn") but the actual file that is being processed (e.g. "_Layout").

The closest I could find was html.ViewDataContainer.ToString() which returns {ASP._Page_Views_Shared__Layout_cshtml} for example, but I don't think that parsing this would be a great idea.

Is this information available in the Html Extension?

Thanks in advance.

Schiavini
  • 2,869
  • 2
  • 23
  • 49

1 Answers1

2

You can create an extension like this,

public static string ViewName(this WebViewPage page)
{
  return Path.GetFileNameWithoutExtension(page.VirtualPath);
}

then from a razor view,

The view name is: @this.ViewName()

or without extension,

The view name is: @Path.GetFileNameWithoutExtension(VirtualPath)
VJAI
  • 32,167
  • 23
  • 102
  • 164