Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Render different Layouts in Asp.NET Core

I want to render empty layout on some pages in my asp.net core app. For this, I have used this code in _ViewStart.cshtml.

@{
    var controller = HttpContext.Current.Request.RequestContext.RouteData.Values["Controller"].ToString();
    string cLayout = "";
    if (controller == "Empty")
    {
        cLayout = "~/Views/Shared/_Empty_Layout.cshtml";
    }
    else
    {
        cLayout = "~/Views/Shared/_Layout.cshtml";
    }
    Layout = cLayout;
}

This code is working fine for Asp.NET MVC App but it gives the error in .NET Core App. The error is The name 'HttpContext' does not exist in the current context

like image 441
Malik Asad Ali Avatar asked May 05 '18 12:05

Malik Asad Ali


1 Answers

HttpContext.Current was a very bad idea from Microsoft, which, fortunately, was not migrated to ASP.NET Core.

You can access RouteData like this:

@Url.ActionContext.RouteData.Values["Controller"]
// or
@ViewContext.RouteData.Values["Controller"]

That said, "empty layout" sounds like you do not want a layout at all. If that's the case, use this:

@{
    var controller = ViewContext.RouteData.Values["Controller"].ToString();
    string layout = null;
    if (controller != "Empty")
    {
        layout = "~/Views/Shared/_Layout.cshtml";
    }
    Layout = layout;
}

null here means "do not use a layout".

like image 149
Camilo Terevinto Avatar answered Oct 17 '22 13:10

Camilo Terevinto