Retrieve the current view name in ASP.NET MVC?

后端 未结 10 868
谎友^
谎友^ 2020-11-28 09:37

I have a partial view (control) that\'s used across several view pages, and I need to pass the name of the current view back to the controller - so if there\'s e.g. validati

10条回答
  •  Happy的楠姐
    2020-11-28 10:11

    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.

提交回复
热议问题