Pass Data from
Controller to View using ViewBag in MVC
In my last article I explain how to send data from view to controller using ViewData. In
this article we will discuss how we can send data using ViewBag. ViewBag used
dynamic property which introduced in C# 4.0 and it is typed object which decide type at runtime. This is the reason we didn't get compile time error.
It is actually maintain a dynamic ViewData Dictionary internally so you can say that it’s a wrapper around
ViewData.
For
example:-
Create a
controller name Home and create view name Index.
In this view
create a list of type string in which stores the Department Name.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcApplication5.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
List<string> dept = new List<string>()
{"HR","Sales","Developer"};
ViewBag.dept_name = dept;
return View();
}
}
}