How to pass data from one view to another in ASP.NET MVC

There are situations when you wish to pass data from one view to another in mvc. This tutorial will guide you through the various ways for doing the same.

You may come across a situation where you may wish to pass data from one 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.

@Html.Partial("viewname", new {item1="value1", item2 = "value2"})

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

@model dynamic

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:

TempData["item1"] = "value1";
TempData["item2"] = "value2";

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:

if(TempData["item1"] != null){
//use TempData["item1"] to retrieve the value

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).

Get updates directly in your inbox

My collection of ideas, thoughts, stories or anything straight from my heart.

Subscribe to Anshul Sojatia

Please provide your email address to subscribe or Login with Twitter to engage in conversation.