This chapter covers
- Using the view bag and temp data to pass data from an action to a view
- Using layouts to define common content
- Using partial views to define reusable sections of content
- Encoding data within views
In this chapter, I describe more of the features provided by Razor Views. I show you how to pass additional data to a view using the view bag and how to use layouts and layout sections to reduce duplication. I also explain how the results from expressions are encoded and how to disable the encoding process. Table 22.1 provides a guide to the chapter.
Table 22.1 Chapter guide (view table figure)
Problem |
Solution |
Listing |
---|---|---|
Providing unstructured data to a view |
Use the view bag. |
5, 6 |
Providing temporary data to a view |
Use temp data. |
7, 8 |
Using the same content in multiple views |
Use a layout. |
9–12, 15–18 |
Selecting the default layout for views |
Use a view start file. |
13, 14 |
Interleaving unique and common content |
Use layout sections. |
19–24 |
Creating reusable sections of content |
Use a partial view. |
25–29 |
Inserting HTML into a response using a Razor expression |
Encode the HTML. |
30–32 |
Including JSON in a view |
Use the JSON encoder. |
33 |
22.1 Preparing for this chapter
This chapter uses the WebApp project from chapter 21. To prepare for this chapter, replace the contents of the HomeController.cs file with the code shown in listing 22.1.