Reputation: 1984
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";
}
}
Upvotes: 0
Views: 956
Reputation: 1984
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.
Upvotes: 0
Reputation: 2046
Use a ternary operator:
@{
Layout = ViewBag.Context == "AA" ? "~/Views/Shared/_Layout_AA.cshtml" : "~/Views/Shared/_Layout.cshtml" ;
}
Upvotes: 0
Reputation: 187
FWIW, you can also do this in the controller:
if (someCondition == "AA")
{
return View("MyView", "~/Views/Shared/_Layout_AA.cshtml");
}
else
{
return View ("MyView", "~/Views/Shared/_Layout.cshtml");
}
Upvotes: 1
Reputation: 1
Use the PageData property (it's something more applicable to ASP.NET WebPages and seldom used in MVC) Set:
@{
PageData["message"] = "Hello";
}
Retrieve
<h2>@PageData["message"]</h2>
Source: How do I set ViewBag properties on _ViewStart.cshtml?
Upvotes: 0