.NET MVC get current page and controller in shared layout

后端 未结 2 412
悲&欢浪女
悲&欢浪女 2021-01-24 02:15

I\'m trying to fetch the current page from my shared layout in .net mvc app so that I can load a different favicon icon for the 2 different pages.

I\'ve tried something

2条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-24 02:40

    You can get your current controller name & action method name from your RouteData dictionary.

    @{
        var controllerName = string.Empty;
        object controllerObj;
        var actionName = string.Empty;
        object actionObj;
    
        if (ViewContext.RouteData.Values.TryGetValue("controller", out controllerObj))
        {
            controllerName = controllerObj.ToString();
        }
    
        if (ViewContext.RouteData.Values.TryGetValue("action", out actionObj))
        {
            actionName = actionObj.ToString();
        }
    }
    

提交回复
热议问题