What I see is a string Layout property. But how can I pass a model to layout explicitly?
Example: Controller:
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;
}
}
Example top of Layout Page
@{
var viewModel = (MainLayoutViewModel)ViewBag.MainLayoutViewModel;
}
Now you can reference the variable 'viewModel' in your layout page with full access to the typed object.
I like this approach because it is the controller that controls the layout, while the individual page viewmodels remain layout agnostic.
Notes for MVC Core
IActionFilter
and doing the exact same work in OnActionExecuting
. Put MyActionFilter
on your MyController
.
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;
}
}
}