Pass Data Across Views In .NET MVC

This series of articles will discuss View related issues of the MVC module.

Introduction

In previous articles, we discussed both View Variables in ASP.NET MVC and View Variables in ASP.NET Core MVC, respectively.  Although each has some distinctive points, both share a lot of common features. In this article, we will discuss something new: pass data across views. We will also summarize some common or important shared features for various vew variables.

  • Introduction
  • A: Brief Summary of ViewData
  • B: Type of ViewData
  • C: Pass Data into _Layout.cshtml Page by ViewData
  • D: Pass Data into _Layout.cshtml Page by Other View Variables
  • Summary

A: Brief Summary of ViewData

We will start our discussion from ViewData, but most or all features are the same for other MVC View Variables. The ASP.NET Core also has the same features. So, we will discuss ViewData in the most, and have the last part to see the extension to other View variables.

B: Type of ViewData

We have discussed ViewData, ViewBag, TempData, Session type features. They are all the Type of Dictionary:

Where the difference between ViewBag and ViewData:

Besides ViewBag, all other View Variables need to be cast before using.

We define a ViewData named "book": as type BookModel with data such as Id = 1:

When we retrieve data, we have to cast the data back to the data type. Otherwise, we will get an error message:

After casting:

C: Pass Data into _Layout.cshtml Page by ViewData

The _layout.cshtml is a shared page by other specific views. It belongs to no Controller or Action, or we can say it belongs to every Controller or Action when the related view is using _layout.cshtml. Therefore, we can pass data into Layout either from the Controller or Action view, that uses the _layout.cshtml, such as, if we have a Contact Us Action:

Or, we can define the ViewData from the Contact Us View:

Both ways will pass the data into Layout page:

Notes

1, We usually introduce the Layout into View by the code in the View as below:

2, in some cases, if we want to make the Layout page(s) dynamic, we can assign the layout to the view through Controller/Action:

3, A related important shared concept for MVC, _Viewstat.cshtml

D: Pass Data into _Layout.cshtml Page by Other View Variables

The same is true for other MVC View Variables, such as ViewBag, TempData, and absolutely Session variable:

Pass TempData to Layout:

Pass ViewData to Layout:

Pass ViewBag to Layout:

Summary

This article discussed using ASP.NET MVC ViewData to pass data into Layout View through either Controller or View.  The features are available or the same as other View Variables in ASP.NET MVC, and the same is true for ASP.NET Core MVC.

Reference