What I see is a string Layout property. But how can I pass a model to layout explicitly?
You can add support for Pages to any ASP.NET Core MVC app by simply adding a Pages folder and adding Razor Pages files to this folder.
The file "_Layout. cshtml" represents the layout of each page in the application. Right-click on the Shared folder in Solution Explorer then go to "Add" item and click on "View". Now the View has been created.
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; } } }
Seems like you have modeled your viewmodels a bit wrong if you have this problem.
Personally I would never type a layout page. But if you want to do that you should have a base viewmodel that your other viewmodels inherits from and type your layout to the base viewmodel and you pages to the specific once.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With