Let's Dig Out What's ViewData, ViewBag and TempData!!!!


MVC 3

ViewData: There are some points about it describe below

  1. Gets or sets a dictionary that contains data to pass between the controller and the view.
  2. Created in Controller where it is passed to the view.
  3. The Objects which accessible using strings as Keys.
  4. It is derived from ViewDataDictonary Class.
  5. Needs to cast values and perform error checking for null values that does not exist.
  6. [Authorize]

public ActionResult Edit(int id)
 {
   Dinner dinner = dinnerRepository.GetDinner(id);
   ViewData["Countries"] = new SelectList(PhoneValidator.AllCountries, dinner.Country);return View(dinner);
 }
   <%= Html.DropDownList("Country", ViewData["Countries"as SelectList) %>

ViewBag:

  1. It acts as a wrapper around the view data object which allows creating dynamic properties for the view bag. It enables great in data accessing facilities.
  2. It access data in dynamic fashion instead of using magic strings
  3. It is easier to store and retrieve key/value pairs in backing store used by view data.
  4. We don't have to type cast. It is better and easier way to access data over viewdata. On the other hand, there are pretty much drawbacks with viewbag such as it does not support intellisense to get the list of properties specified in the controller. It also does not accepts the dynamic data to pass into html helper methods of System.Web.Mvc.HtmlHelpers.

public ActionResult Index()
{
    List<string> colors = new List<string>();
    colors.Add("red");
    colors.Add("green");
    colors.Add("blue");
    ViewBag.ListColors = colors; //colors is List
    ViewBag.DateNow = DateTime.Now;
    ViewBag.Name = "Raj";
    ViewBag.Age = 25;
    return View();
}
<p>
    My name is
    <b><%: ViewBag.Name %></b>,
    <b><%: ViewBag.Age %></b> years old.
    <br />
    I like the following colors:
</p>
<ul id="colors">
<% foreach (var color in ViewBag.ListColors) { %>
    <li>
        <font color="<%: color %>"><%: color %></font>
    </li>
<% } %>
</ul>
<p>
    <%: ViewBag.DateNow %>
</p>

TempData:

  1. It is stored in session, the way to persist data across single request. It is used to store the validation errors before redirecting to the previous page.
  2. It mainly deals with processing current and subsequent request when you are sure that it is redirecting to the next view. They are destroyed after the request made.
  3. It is available for temporary for a single request where it passes messages between controllers
  4. It is a type of fire and forget mechanism. If you want to use session or high scale in throughput do not hesitate to TempData.
  5. [ControllerAction]

public void Create(int id)
{
  Product prod = new Product();
  prod.UpdateFrom(Request.From);
  if(prod.Validate())
  {
     prod.Save();
     RedirectToAction("List");
  }
  else
  {
    TempData["ErrorMessage"] = "Invalid entry. Try again.";
    RedirectToAction("New");
  }
}
//New.aspx:
  <% if(TempData.ContainsKey("ErrorMessage") { %>
       Error happened: <%= TempData["ErrorMessage"] %>
  <% }  %>
 rest of the HTML ...
 

Up Next
    Ebook Download
    View all
    Learn
    View all
    MVC Corporation is consulting and IT services based company.