Saturday, 4 August 2012

Difference between MVC- ViewData and ViewBag?

public abstract class ControllerBase : IController
{
public dynamic ViewBag { get; }
public ViewDataDictionary ViewData { get; set; }

}

ViewBag:

viewBag is a dynamic Property which is used to pass data from view to controller.
Like
            ViewBag.FirstName = "kasibabu";
            ViewBag.LastName = "viswanath";
            ViewBag.Age = 26;
            ViewBag.Address = ViewBag.FirstName + ViewBag.LastName; // Dynamic Property

            ViewData["Age"] = ViewBag.Age;  // which is key/valued collection.

so we can access the Data from view at Runtime.

Like
        @ViewBag.Address---------à kasibabuviswanadh // Runtime passing data
        @ViewData["Age"]---------à key/ value based collection.

In ViewBag which create an anonymous type at runtime then pass data dynamically to view.

come to ViewData which holds data like a Session which stores data to based on key.

ViewData :


ViewData is of type ViewDataDictionary. which is also used to pass data from control to view

As well how to

        public ActionResult Index()
        {

            List<string> countries = new List<string>();
            countries.Add("India");
            countries.Add("Usa");
            countries.Add("UK");
ViewBag.Countries = countries;         //   ViewData["countries"] = countries;

            return View();
        }
<h6>
   <ol title="Some countries">
      @foreach (var item in ViewBag.Countries)
      {
         <li> @item</li>
      }
    </ol>
</h6>

 //   ViewData["countries"] = countries;

<ol title="Some countries">
      @foreach (var item in ViewData["countries"] as List<string>) //weak -typing
      {
         <li> @item</li>
      }

    </ol>

Yes the above ViewData way while converting we need to specify as strings.
So we can cay this is not a tightly coupled view.


as well as strongly typed view also is possible with the help of specified Model.

@model IEnumerable<FutureisMVC.Models.RegisterModel>

@model IEnumerable<FutureisMVC.Models.CarModel>

----ect.


which is preferable is based on scenerio : 




No comments:

Post a Comment