Difference/Similarities between ViewBag and ViewData in MVC

Differences
ViewData
ViewBag
ViewData is a dictionary of objects that are stored and retrieved using strings as keys.
Such as:

ViewData[“key”]=value; // stored value in ViewData

String n = ViewData[“Key”]; // Retrieve Data





ViewBag uses the dynamic feature that was introduced in to c# 4. It allows an object to have properties dynamically add to it.

ViewBag.name = “Jacob”;

// here name is the dynamic property of //ViewBag object

Similarities
·         Both ViewData ans ViewBag are used to pass data from a controller to a View.
·         Both ViewData & ViewBag does not provide compile time error checking

Example
Controller class
  public ActionResult Index()
        {
            ViewBag.country = new List<string>()
            {
                "USA",
                "INDIA",
                "UK"
            };
            return View();
        }

View
<ul>
    @foreach (string  country in ViewBag .coun)
    {
        <li>@country</li>
    }



</ul>

·         Note  : In View here you are accessing dynamic property of coun , which is not existing in Controller class. But in case Both ViewData & ViewBag does not provide compile time error checking




Difference/Similarities between ViewBag and ViewData in MVC Difference/Similarities between ViewBag and ViewData in MVC Reviewed by Jacob Lefore on October 09, 2013 Rating: 5

No comments