nanonerd nanonerd - 9 days ago 6
C# Question

add logic to _ViewStart.cshtml

is there a way to add logic in the _ViewStart.cshtml file to drive which _Layout file to use?

Conceptually, I want to do the code below (ViewBag.Context is determined in the Home controller). But I get a red squiggly under ViewBag (does not exist in current context). I guess this is a problem because this view page doesn't know which controller/method is calling it.

@{if (ViewBag.Context == "AA")
{
Layout = "~/Views/Shared/_Layout_AA.cshtml";
}
else
{
Layout = "~/Views/Shared/_Layout.cshtml";
}
}

Answer

Some of you are not seeing "But I get a red squiggly under ViewBag (does not exist in current context). I guess this is a problem because this view page doesn't know which controller/method is calling it."

My solution was to embed the value in a cookie while in the controller at the start. Then in the _ViewStart.cshtml file, I retrieve the cookie value and can now use it to dictate my layout logic.