The ViewBag Property in ASP.NET MVC 3 is Just Syntactic Sugar

The MVC Controller can pass data to the View using multiple ways. It can either use a strongly typed object or use a global dictionary such as ViewData etc. ASP.NET MVC 3 introduces a dictionary in the Controller base class called the ViewBag property to access view data.

The new ASP.NET MVC 3 ViewBag property strictly speaking is just syntactic sugar – with a terse syntax when compared to the ViewData property in MVC 2. It can only be used in .NET 4 and above. It is actually a wrapper over ViewData and internally, the ViewBag properties are stored as name/value pairs in the ViewData dictionary.

This ViewBag property is defined as a dynamic type and we can create new properties in it by simply assigning arbitrary values to it. We can then access these values using the Controller.ViewBag property. Here’s an example of using both the ViewBag and ViewData. Observe the syntax difference

asp.net mvc viewbag

To consume the ViewBag in a Razor view, you would use

@ViewBag.Message

Let us see how to assign arbitrary properties to the ViewBag and access the values in the View. In your controller, use the following

public ActionResult Index()
        {
            var dt = DateTime.Now; 
            ViewBag.DateRightNow = dt;
            ViewBag.Greeting = dt.Hour < 12 ? "Morning" : "Evening";
            return View();
        }

In your Razor View (Index.cshtml), access these values as

<h2>@ViewBag.Greeting ! Today is @ViewBag.DateRightNow.DayOfWeek</h2>

OUTPUT

asp.net mvc viewbag

ViewBag vs ViewData
  • Both ViewBag and ViewData do not have compile time checking of properties (no compile time safety).  
  • There’s not much of a performance difference when using one over the other 
  • You do not need to cast the property value from the ViewBag as it is a dynamic type. Since ViewData is an object type, so casting is needed. 
  • ViewBag works with MVC 3 and .NET 4 whereas ViewData works with any version of MVC and .NET 2.

Since there isn’t much of a difference except for the terse syntax, it’s just a preference of the developer to use ViewBag or ViewDate.





About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

No comments: