Schiavini
Schiavini

Reputation: 2939

HtmlHelper extension to find view name

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.

Upvotes: 1

Views: 470

Answers (1)

VJAI
VJAI

Reputation: 32758

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)

Upvotes: 2

Related Questions