Wednesday 24 May 2017

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

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
1
@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

1
2
3
@model dynamic
<div>@Model.item1</div>
<div>@Model.item2</div>
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:

1
2
3
4
5
@{
TempData["item1"] = "value1";
TempData["item2"] = "value2";
}
@Html.Partial("viewname")
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:

1
2
3
4
5
@{
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).


 Happy Programming!!

Don’t forget to leave your feedback and comments below!

If you have any query mail me to Sujeet.bhujbal@gmail.com     

Regards
Sujeet Bhujbal
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------