.NET MVC get current page and controller in shared layout

后端 未结 2 384
悲&欢浪女
悲&欢浪女 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();
        }
    }
    
    0 讨论(0)
  • 2021-01-24 02:47

    I use something this to change my layout for some particular reasons with users that are not logged in or hasn't got claims yet.

    Take consideration, Values will are keys where:

    Value[0] = controller  
    Value[1] = action
    

    using this logic:

     if (ViewContext.RouteData.Values.Where(v => v.Key == "action").FirstOrDefault().Value.ToString() == "MyAction")
        {
            Layout = "_Layout_MyOtherLayout";
        }
        else
        {
            Layout = "_Layout";
        }
    
    0 讨论(0)
提交回复
热议问题