Header add

In this article we will discuss How to use ViewBag in ASP.Net Core MVC.

Here we discuss What is ViewBag with example of ViewBag in ASP.NET Core MVC.

Before start this article, please visit our previous article ASP.Net Core MVC: Pass (Get) data from View to Controller

What is ViewBag

The ViewBag in ASP.NET MVC is used to transfer temporary data (which is not included in the model) from the controller to the view. Internally, it is a dynamic type property of the ControllerBase class which is the base class of the Controller class. ViewBag only transfers data from controller to view, not visa-versa.
  • ViewBag is a Wrapper built around ViewData.
  • ViewBag is a dynamic property and it makes use of the C# 4.0 dynamic features.
  • While retrieving, there is no need for Type Casting data.
  • ViewBag is available only for Current Request. It will be destroyed on redirection.

ViewBag Example

Let's create a ASP.NET Core MVC project and pass data from controller to view.

Controller

In the controller we need to pass the data using ViewBag object


View

In the view page we called here @ViewBag.Message, we need to remember whatever name is assign in ViewBag the same name must use to retrieve the data from view page and once the data can read then the ViewBag value is destroy.


When we run the application we can see the output like below.

How to use ViewBag in ASP.Net Core MVC



Post a Comment

Previous Post Next Post