22 Using controllers with views, part II

 

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.

22.1.1 Dropping the database

 

22.1.2 Running the example application

 
 
 

22.2 Using the view bag

 
 
 
 

22.3 Using temp data

 

22.4 Working with layouts

 
 
 

22.4.1 Configuring layouts using the view bag

 
 
 
 

22.4.2 Using a view start file

 
 
 

22.4.3 Overriding the default layout

 
 
 

22.4.4 Using layout sections

 
 
 

22.5 Using partial views

 

22.5.1 Enabling partial views

 
 

22.5.2 Creating a partial view

 
 

22.5.3 Applying a partial view

 
 

22.6 Understanding content-encoding

 
 
 
sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage
test yourself with a liveTest