3 different ways to pass data from controller to view.
3 ways to pass data from controller to view
In this article we will discuss three different ways to pass
data from controller to view in MVC web application. Those three approaches are
, using ViewBag ,ViewData and TempData
ViewBag:-
ViewBag is a dynamic approach to pass data.
It’s available only in MVC3 .
It does not require type casting for complex data type.
Means there is no type cast needed even if we pass object of a class.
It does not retain value in redirection.
ViewData:-
It store data in Key value pair(Like session)
Type casting is needed for complex data type
ViewData cannot retain it’s value in redirection.
TempData:-
Type cast is needed for complex data type.
Store data using Kay(Like session)
Can able to retain value in redirection.
So, those are the
basic difference among them. Now we will implement them in a small example
Create Person class in Model
using System;
using System.ComponentModel.DataAnnotations;
namespace PersonModel
{
public class Person
{
public String Name { get; set; }
public String Surname { get; set;}
}
}
This is our small person class containing two properties
called Name and Surname
Create controller class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVCTest.Controllers
{
public class PersonController : Controller
{
public ActionResult ShowUser()
{
PersonModel.Person P = new PersonModel.Person();
P.Name = "Sourav";
P.Surname = "Kayal";
ViewBag.Person = P;
ViewData["P"] = P;
TempData["P"] = P;
return View("Show");
}
}
}
In this Person controller we have implemented ShowUser()
action which will assign object of Person class in ViewBag, ViewData and
TempData and it will call to Show view.
Create View
@model PersonModel.Person
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Show</title>
</head>
<body>
<div>
@{
var ViewBagValue = ViewBag.Person;
var ViewDataValue =(PersonModel.Person) ViewData["P"];
var TempDataValue =(PersonModel.Person) TempData["P"];
}
Name is :- @ViewBagValue.Name<br/>
Name is:- @ViewDataValue.Name <br />
Name is:- @TempDataValue.Name <br />
</div>
</body>
</html>
Here we are extracting value from three different variables.
We can see there is no casting needed for ViewBag where casting needed for
ViewData and TempData
Here is sample output:-

Conclusion
Here we have learned how to pass data from controller to view in various ways. Hope you have enjoyed it.