Join Jess Chadwick for an in-depth discussion in this video Sharing data between layouts and views, part of ASP.NET Core: Razor Pages.
- In the last video, I was able to specify some default text to display when pages did not provide content for an optional section. While that helps eliminate errors when pages do not define sections, it'd still be nice to be able to define the text of the title without having to define all of the markup in the title section. Luckily, Razor offers a way to share data between a page and its layout, and it's called ViewData. A dictionary that is accessible from both the page and its layout through a property named ViewData on each of them.
Thus, whenever you set a value on this dictionary in a page, that value will also be available to the layout. So, in order to pass data between the page and the layout, we simply assign a value to the ViewData dictionary, like this. Once I've assigned this property in a page, it'll be available in the layout. To use it, I just reference it like any other variable.
Now, when I refresh the page, I can see that new title being displayed. Set in a simple and effective way without having to define the markup for the entire section.
- Creating a new application
- Setting up pages
- Rendering dynamic content
- Reusing markup with layouts
- Increasing the maintainability of pages
- Processing data
- Validating input
- Securing an application