How to use ViewBag in ASP .Net MVC C#?

CsharpServer Side ProgrammingProgramming

ViewBag uses the dynamic feature that was introduced in to C# 4.0. It allows an object to have properties dynamically added to it. 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 values will be null if redirection occurs. ViewBag is able to set and get value dynamically and able to add any number of additional fields without converting it to strongly typed.

Storing data in ViewBag −

ViewBag.Counties = countriesList;

Retrieving data from ViewBag −

string country = ViewBag.Countries;

Controller

Example

using System.Collections.Generic;
using System.Web.Mvc;
namespace DemoMvcApplication.Controllers{
   public class HomeController : Controller{
      public ViewResult Index(){
         ViewBag.Countries = new List<string>{
            "India",
            "Malaysia",
            "Dubai",
            "USA",
            "UK"
         };
         return View();
      }
   }
}

View

@{
   ViewBag.Title = "Countries List";
}
<h2>Countries List</h2>
<ul>
@foreach(string country in ViewBag.Countries){
   <li>@country</li>
}
</ul>

Output

raja
Published on 24-Sep-2020 14:37:16
Advertisements