Retrieve the current view name in ASP.NET MVC?

后端 未结 10 894
谎友^
谎友^ 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条回答
  •  旧时难觅i
    2020-11-28 10:27

    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()
    

提交回复
热议问题