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

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;
using System.Collections.Generic;
using System.Web.Mvc;
namespace CsharpCode_DemoMvcApplication.Controllers{
   public class HomeController : Controller{
      public ViewResult Index(){
         ViewBag.Countries = new List<string>{
         return View();
   ViewBag.Title = "Countries List";
<h2>Countries List</h2>
@foreach(string country in ViewBag.Countries){

0 Comment's

Comment Form