Comparison between ViewBag and ViewData in MVC


Introduction

In my recent free E-Book titled “Razor View Engine in MVC 3”, written some lines on “ViewBag and ViewData”, a reader named “Krish” asked me a question as follows:

Krish: Nice one book to learn MVC and Razor, thanks for it. But the last statement you written "There is no any significant advantage in using ViewBag over ViewData, perhaps a few fewer key strokes, but nothing more." But ViewBag is using the concept of C # 4.0 i.e. dynamic creations of properties which can replace the strongly typed view.
What you think about this. Thanks I got the book.

And what I replied to him is

Author: Nice point to discuss on, it’s a most frequent question in online forums. Look at the difference "ViewData is a dictionary object that you put data into, which then becomes available to the view. ViewData is a derivative of the ViewDataDictionary class, so you can access by the familiar "key/value" syntax. The ViewBag object is a wrapper around the ViewData object that allows you to create dynamic properties for the ViewBag". I hope your point is clear now. Please reply the same.

After above discussion I decided to post some real examples on this point which I missed to put in that free e-book. So, let’s take a look at the discussion.

As we know there no any technical differences between both terms that which one to choose while developing our MVC application however there is some critical differences that we should remember.

First One

ViewBag only works when the key which is being accessed is valid identifier.
For example, if you place a value in

ViewBag[“Identified having space”],

then we can’t access that value using ViewBag.

Second One

Remember, in case your parameter is dynamic then your program will fail if you are using ViewBag. For example,

@Html.TextBox(“mobile”, ViewBag.Mobile)

Above code will always fail, to fix this you need to use either ViewData[“Mobile”] or use casing in ViewBag like (string)ViewBag.Mobile.
Thanks for reading this post.

Comments

Popular posts from this blog

Migrating database from ASP.NET Identity to ASP.NET Core Identity

Customize User's Profile in ASP.NET Identity System