Malik Asad Ali
Malik Asad Ali

Reputation: 113

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

Upvotes: 5

Views: 3262

Answers (1)

Camilo Terevinto
Camilo Terevinto

Reputation: 32058

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".

Upvotes: 8

Related Questions