How do we transmit data from controller to view in MVC?
- Posted on
- ASP.NET MVC
- By Deepak Talwar
Data transfer from controller to view in Model View Controller (MVC) has three options. ViewData, ViewBag, and TempData.

ViewData
- The ViewData is used to move data from controller to view.
- The ViewData is a dictionary of objects that are derived from the "ViewDataDictionary" class and it will be accessible using strings as keys.
- ViewData contains a null value when redirection occurs.
- ViewData requires typecasting for complex data types.
public class ExampleController : Controller{
public ActionResult Index() {
ViewData["Message"] = "This is about ViewData in ASP.NET MVC!!!";
return View();
}
}
<div>
@ViewData["Message"]
</div>
ViewBag
- ViewBag is mainly used for the passing of value from the Controller to View.
- ViewBag is just a dynamic wrapper around ViewData and exists only in ASP.NET MVC 3. ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0.
- ViewBag doesn't require typecasting for complex data types.
- ViewBag also contain a null value when redirection occurs.
public class ExampleController : Controller{
public ActionResult Index() {
ViewBag.Message = "This is about ViewBag ASP.NET MVC!!";
return View();
}
}
<div>
@ViewBag.Message
</div>
ViewData and ViewBag are comparable, but TempData does more.
TempData
- TempData is a dictionary object useful for the temporary storage of data. It is an instance of the Controller base class. It is useful in storing the data for the duration of an HTTP request, or we can say that it can store live data between two consecutive requests of HTTP.
- It is also useful in passing the state between action methods. TempData can be used only with the subsequent and current requests. It will make use of a session variable for storing the data. TempData needs typecasting during data retrieval.
- Use TempData when you need data to be available for the next request, only. In the next request, it will be there but will be gone after that.
- TempData is used to pass data from the current request to the subsequent request, in other words in case of redirection. That means the value of TempData will not be null.
public ActionResult FirstRequest(){
List<string> TempDataDemo = new List<string>();
TempDataDemo.Add("Harish");
TempDataDemo.Add("Nagesh");
TempDataDemo.Add("Rakshith");
TempData["EmployeeName"] = TempDataDemo;
return View();
}
public ActionResult ConsecutiveRequest(){
List<string> modelData = TempData["EmployeeName"] as List<string> ;
TempData.Keep();
return View(modelData);
}
s