Friday, September 19, 2014

Difference between ViewData and ViewBag In MVC

ViewData ,ViewBag and TempData

When passing information from an action method to a view, you basically have three options:

1. Use the ViewDatadictionary
2. Use  ViewBag(starting in MVC 3)
3. Use a strongly typed view with a view model object




       ViewData and ViewBag allow you to add information (primitive types such as integers or even complex objects) that will later be accessible to the view for generating HTML.

        ViewData is simply a dictionary that uses the key/value pattern. An example of how to use ViewData is provided in below example code. Note that the information in the ViewData dictionary is simply added by giving it a name and setting its value.



Example for ViewData:

In Action Method
public ActionResult ShowError()
{
ViewData["ErrorCode"] = 12345;
ViewData["ErrorDescription"] = "Something bad happened";
ViewData["ErrorDate"] = DateTime.Now;
ViewData["Exception"] = new Exception();
return View();
}

In ViewPage

@* View *@
<h1>An error was found</h1>
<h2>Error Code: @ViewData["ErrorCode"]</h2>
<h2>Error Date: @ViewData["ErrorDate"]</h2>
<h2>@ViewData["ErrorDescription"]</h2>



ViewBag:

ViewBag is different from ViewData in the sense that it implements the dynamic features introduced in C# 4. Basically, the difference is that properties can be added to ViewBag dynamically. Following example  shows  modify to above example using ViewBag.

Example for ViewBag:

In Action Method
public ActionResult ShowError()
{
ViewBag.ErrorCode = 12345;
ViewBag.ErrorDescription = "Something bad happened";
ViewBag.Exception = new Exception();
return View();
}

In View 
<h1>An error was found</h1>
<h2>Error Code: @ViewBag.ErrorCode</h2>
<h2>@ViewBag.ErrorDescription</h2>



One last thing to consider when using ViewData and ViewBag is that the information in the dictionary is lost after the view is rendered.

 In this scenario, you will have to use a different object that is designed to have a short
 life but is capable of surviving redirects. The object is TempData, which, as opposed to ViewData, is  stored in the current session instead of a dictionary. Use TempData with caution, as the information  is promptly discarded once the redirect is complete. If you refresh the page, the information in  TempData won’t be available.


No comments:

Post a Comment