Retrieve the current view name in ASP.NET MVC?

后端 未结 10 862
谎友^
谎友^ 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条回答
  • 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()
    
    0 讨论(0)
  • 2020-11-28 10:28

    Shouldn't you be using a validation method like Nerd Dinner implements?

    That way you don't actually need to do all this and you can just return the View.

    0 讨论(0)
  • 2020-11-28 10:29

    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");
    }
    
    0 讨论(0)
  • 2020-11-28 10:31

    If you want to get the filename from within a partial view, this seems to work:

    public static class HtmlHelperExtensions
    {
        public static string GetViewFileName(this HtmlHelper html, object view)
        {
            return @"\\"+ view.GetType().FullName.Replace("ASP._Page_", "").Replace("_cshtml", ".cshtml").Replace("_", @"\\");
        }
    }
    

    And in the partial view, you should do something like this:

    var filename = Html.GetViewFileName(this);
    

    or this:

    @Html.GetViewFileName(this)
    

    Please do comment if this is not a good approach - any alternatives?

    0 讨论(0)
提交回复
热议问题