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
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With