Get current action and controller name in View in ASP.NET MVC

Being able to get action or controller name on view might come useful when you are using layout for every view(except partial views) in your application.

Layout view
 @if (Request.IsAuthenticated)
                        {
                            <ul>
                                <li>
                                    @Html.ActionLink("Dashboard", "Index", "Home")
                                </li>
                                <li>
                                    @Html.ActionLink("Account", "Manage", "Account")
                                </li>
                                <li>
                                    @Html.ActionLink("GetClients", "Index", "Client")
                                </li>
                                <li>
                                    @Html.ActionLink("Setting", "ListingForOrganisation", "Settings")
                                </li>
                               
                                @if (HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString() == "Client")
                                {
                                <li><span>Add Client</span>
                                    <ul>
                                        <li>
                                            @Html.ActionLink("Temporary client", "AddTemporaryClient", "Client")
                                        </li>
                                        <li>
                                            @Html.ActionLink("Permanent", "AddPermanentClient", "Client")
                                        </li>
                                    </ul>
                                </li>
                                }
                            </ul>
                        }

(HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString() == "Client")
will check if request came from Client controller and if so extra feature will appear.

To get action name replace simply use 
(HttpContext.Current.Request.RequestContext.RouteData.Values["action"].ToString() == "Action name") 



Comments