Getting controller name from razor

前端 未结 6 481
旧时难觅i
旧时难觅i 2020-12-03 13:11

I seem to be having a difficult getting something that should be easy. From within my view, using Razor, I\'d like to get the name of the current controller. For example, if

相关标签:
6条回答
  • 2020-12-03 13:43

    To remove need for ToString() call use

    @ViewContext.RouteData.GetRequiredString("controller")
    
    0 讨论(0)
  • 2020-12-03 13:50

    Also if you want to get the full controller's name (with "Controller" ending) you can use:

    ViewContext.Controller.GetType().Name
    
    0 讨论(0)
  • 2020-12-03 13:53

    @ViewContext.RouteData.Values["controller"].ToString();

    0 讨论(0)
  • 2020-12-03 14:02
    @{ 
        var controllerName = this.ViewContext.RouteData.Values["controller"].ToString();
    }
    

    OR

    @{ 
        var controllerName = HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString();
    }
    
    0 讨论(0)
  • 2020-12-03 14:02

    An addendum to Koti Panga's answer: the two examples he provided are not equivalent.

    This will return the name of the controller handling the view where this code is executed:

    var handlingController = this.ViewContext.RouteData.Values["controller"].ToString();
    

    And this will return the name of the controller requested in the URL:

    var requestedController = HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString();
    

    While these will certainly be the same in most cases, there are some cases where you might be inside a partial view belonging to a different controller and want to get the name of the controller "higher-up" in the chain, in which case the second method is required.

    For example, imagine you have a partial view responsible for rendering the website's menu links. So for every page in your website, the links are prepared and passed to the view from an action called SiteMenuPartial in LayoutController.

    So when you load up /Home/Index, the layout page is retrieved, the SiteMenuPartial method is called by the layout page, and the SiteMenuPartial.cshtml partial view is returned. If, in that partial view, you were to execute the following two lines of code, they would return the values shown:

    /* Executes at the top of SiteMenuPartial.cshtml */
    @{
        // returns "Layout"
        string handlingController = this.ViewContext.RouteData.Values["controller"].ToString();
    
        // returns "Home"
        string requestedController = HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString();
    }
    
    0 讨论(0)
  • 2020-12-03 14:02
    @HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString();
    

    MVC 3

    @ViewContext.Controller.ValueProvider.GetValue("controller").RawValue
    

    MVC 4.5 Or MVC 5

    @ViewContext.RouteData.Values["controller"].ToString();
    
    0 讨论(0)
提交回复
热议问题