.NET MVC get current page and controller in shared layout

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 like following:

@if (Request.Url.AbsoluteUri.ToString().ToLower().Contains("/Analyze/Index"))
{

    <link rel="icon" type="image/png" href="/favicon.png" rel="nofollow noreferrer noopener" />
}

But this doesn’t works…

How can I fetch the current controller and view that user is on while browsing the website so that I can load this favicon in his/her browser?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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

Method 2

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";
    }


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x