Retrieve the current view name in ASP.NET MVC?

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("https://stackoverflow.com/"));
            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.

Leave a Comment