How to get the current view name in asp.net MVC 3?

How can I get the current view name regarding to current URL, in asp.net MVC 3 using Razor engine?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

No idea why you would need to get the current view name but you could use the VirtualPath property inside a view. Normally it’s more useful to know the current action or controller. But anyway, here’s how to get the current view name:

@VirtualPath

and if you wanted to get only the filename:

@Path.GetFileName(Server.MapPath(VirtualPath))

and without the extension:

@Path.GetFileNameWithoutExtension(Server.MapPath(VirtualPath))

Method 2

I’ve also tested this code, and I could do something with it.
But, I’m not sure if is this a good solution or not.

For example, I need to detect the Contacts view located in Home directory. So I wrote:

if (@Request.RawUrl == "/Home/Contacts")
{
   // do something
}

Method 3

You can get it from RequestContext.RouteData
specifically, its Values collection contains “controller” and “action” keys
i.e.
RequestContext.RouteData.Values[“controller”]
RequestContext.RouteData.Values[“action”]

Method 4

ASP.NET Core’s equivalent:

@ViewContext.ExecutingFilePath

Output is like this:

/Views/Shared/String.cshtml

The rendering of a view may involve one or more files (e.g. _ViewStart, Layouts etc).
This property contains the path of the file currently being rendered.

ViewContext.ExecutingFilePath Property


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x