w3resource

ViewBag - ASP.NET MVC


In the previous tutorials, we learnt that with model objects, we can pass data from the controller to the views. But there exist some scenarios when we will just want to move some tiny bits of information to the view, where we may not really require a model a object, in such cases ViewBag is the way to go.

ViewBag is mostly useful when we want to transfer temporary data (which is not included in model) from the controller to the view. The ViewBag is a dynamic container. It is a type property of Controller Base class from which all other controllers inherit from.

The diagram below illustrates the use of ViewBag.

asp.net use of ViewBag

In the screenshot figure, we attached the Name property to the ViewBag with the dot notation and then assigned it to a string value "Vita". This can be accessed in the view like @ViewBag.Name. (recall that the @ is a symbol used to access server-side variables from the view)

We described view bag as a dynamic container, thus we can assign a primitive or a complex type object as a value to ViewBag property.

We can also assign any number of properties and values to ViewBag. If we should assign the same property name multiple times to ViewBag, then ViewBag will only consider the last value assigned to it.

Points to note:

ViewBag operates works as single duplex communicator. That is, it only sends data from the controller to the view, and not visa-versa. When redirection occurs, the values stored in the ViewBag values will be lost.

The following example demonstrates how to transfer data from controller to view using ViewBag.

Example: Set ViewBag in Action method

namespace ActivityTabs.Controllers
{
    public class ActivityController : Controller
    {
        IList<Activity> activityList = new List<Activity>() { 
                    new Activity(){ ID=1, ActivityName="Write C#", Time = 21 },
                    new Activity(){ ID=2, ActivityName="Read Poems",Time = 25},
                    new Activity(){ ID=3, ActivityName="Play Games", Time = 20 },                };
        // GET: Activities
        public ActionResult Index()
        {
            ViewBag.TotalActivities = activityList.Count();
            return View();
        }

    }
}

In the above code snippet, we want to display the total number of activities in a view for the controller. So, we have attached the TotalAvtivities property to the ViewBag and assigned the activity count using activityList.Count().

Now, in the Index.cshtml view, you can access ViewBag.TotalActivities property and display all the activities count as shown below.

Example: Accessing ViewBag in a View

<label>Total Activities:</label>@ViewBag.TotalActivities

Output:

Total Activities: 3

ViewBag doesn't require typecasting while retrieving values from it. In the next tutorials we will look at other options of moving data from controller to the views that may require typecasting.



Inviting useful, relevant, well-written and unique guest posts