Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <ol> <li>Add a property to your controller (or base controller) called MainLayoutViewModel (or whatever) with whatever type you would like to use.</li> <li>In the constructor of your controller (or base controller), instantiate the type and set it to the property.</li> <li>Set it to the ViewData field (or ViewBag)</li> <li>In the Layout page, cast that property to your type.</li> </ol> <p>Example: Controller:</p> <pre><code>public class MyController : Controller { public MainLayoutViewModel MainLayoutViewModel { get; set; } public MyController() { this.MainLayoutViewModel = new MainLayoutViewModel();//has property PageTitle this.MainLayoutViewModel.PageTitle = "my title"; this.ViewData["MainLayoutViewModel"] = this.MainLayoutViewModel; } } </code></pre> <p>Example top of Layout Page</p> <pre><code>@{ var viewModel = (MainLayoutViewModel)ViewBag.MainLayoutViewModel; } </code></pre> <p>Now you can reference the variable 'viewModel' in your layout page with full access to the typed object.</p> <p>I like this approach because it is the controller that controls the layout, while the individual page viewmodels remain layout agnostic.</p> <p><strong>Notes for MVC Core</strong> <hr /> Mvc Core appears to blow away the contents of ViewData/ViewBag upon calling each action the first time. What this means is that assigning ViewData in the constructor doesn't work. What does work, however, is using an <code>IActionFilter</code> and doing the exact same work in <code>OnActionExecuting</code>. Put <code>MyActionFilter</code> on your <code>MyController</code>.</p> <pre><code>public class MyActionFilter: Attribute, IActionFilter { public void OnActionExecuted(ActionExecutedContext context) { } public void OnActionExecuting(ActionExecutingContext context) { var myController= context.Controller as MyController; if (myController!= null) { myController.Layout = new MainLayoutViewModel { }; myController.ViewBag.MainLayoutViewModel= myController.Layout; } } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload