Retrieve the current view name in ASP.NET MVC?
If you just want the action name then this would do the trick:
public static string ViewName(this HtmlHelper html)
{
return html.ViewContext.RouteData.GetRequiredString("action");
}
I had the same problem and that's how I solved it:
namespace System.Web.Mvc
{
public static class HtmlHelperExtensions
{
public static string CurrentViewName(this HtmlHelper html)
{
return System.IO.Path.GetFileNameWithoutExtension(
((RazorView)html.ViewContext.View).ViewPath
);
}
}
}
Then in the view:
var name = Html.CurrentViewName();
or simply
@Html.CurrentViewName()
Well if you don't mind having your code tied to the specific view engine you're using, you can look at the ViewContext.View
property and cast it to WebFormView
var viewPath = ((WebFormView)ViewContext.View).ViewPath;
I believe that will get you the view name at the end.
EDIT: Haacked is absolutely spot-on; to make things a bit neater I've wrapped the logic up in an extension method like so:
public static class IViewExtensions {
public static string GetWebFormViewName(this IView view) {
if (view is WebFormView) {
string viewUrl = ((WebFormView)view).ViewPath;
string viewFileName = viewUrl.Substring(viewUrl.LastIndexOf('/'));
string viewFileNameWithoutExtension = Path.GetFileNameWithoutExtension(viewFileName);
return (viewFileNameWithoutExtension);
} else {
throw (new InvalidOperationException("This view is not a WebFormView"));
}
}
}
which seems to do exactly what I was after.