0

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";
    }
}
tereško
  • 58,060
  • 25
  • 98
  • 150
nanonerd
  • 1,964
  • 6
  • 23
  • 49

4 Answers4

1

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");
}
BasicIsaac
  • 187
  • 8
0

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?

Community
  • 1
  • 1
skhan
  • 1
0

Use a ternary operator:

@{
   Layout = ViewBag.Context == "AA" ? "~/Views/Shared/_Layout_AA.cshtml" : "~/Views/Shared/_Layout.cshtml" ;
  }
Rafael Carvalho
  • 2,036
  • 2
  • 15
  • 19
0

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.

nanonerd
  • 1,964
  • 6
  • 23
  • 49