.NET MVC get current page and controller in shared

2019-03-06 05:38发布

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

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?

1条回答
Root(大扎)
2楼-- · 2019-03-06 06:05

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();
    }
}
查看更多
登录 后发表回答