You may come across a situation where you may wish to pass data from one asp.net razor view to another. There are a number ways of doing the same.

1. Using Partial Views

One commonly used way to pass data from one view to another is you can create a dynamic anonymous object and pass it to the partial function.

Now in your partial view, you can use dynamic keyword to access the data in the partial view. The view should look like

2. Use TempData

This is useful when your partial view accepts model of another type or you wish to use any existing partial view and pass data to it. TempData uses an indexed dictionary with key and value to store the data.

So in your view where you wish to include the partial view, you write it like:

Note how we used string keys to define our data values. You can create as many keys as you want.

Note that if you add the same key again, it’ll overwrite the previous value.

Now in your partial view, you can use the data as:

A null check before retrieval of data ensures that the Razor engine doesn’t throw any error in case no data has been passed.

Note that life of TempData  is only till the current request completes. It’s not available thereafter

3. Using Session Variables

The usage syntax of session variables is similar to TempData except that the lifetime of a session variable is for the entire browser session (or an expiration time of 20 minutes default).