1. Both Viewdata and ViewBag are used to pass data from Controller to view. Viewdata is a dictionary of objects that are stored and retrieved using string as keys.
ViewData[“yourKey”]=”Some Value” ;
ViewBag.yourProperty=”Some data”;
2. ViewBag uses the dynamic feature that was introduced in C# 4. It allows an object to have properties dynamically added to it.
3. Both ViewBag and Viewdata does not provide compile time error checking. You will get error only at runtime error.
Note: To pass data from Controller to view, it is always good practice to use strongly typed view model over ViewBag or Viewdata. Strongly typed view models provide compile type error checking.
Sample code for ViewBag
Step1 : Create Controller like this
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace WebApplication7.Controllers { public class HomeController : Controller { // GET: Home public ViewResult Index() { ViewBag.Country = new List<string>() { "India", "Nepal", "US", "UK" }; return View(); } } }
Step 2: Write the code in View like this
@{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> <h2>Country List</h2> </head> <body> <div> <ul> @foreach (var strCountry in ViewBag.Country) { <li> @strCountry </li> } </ul> </div> </body> </html>
Sample Code for Viewdata
Step 1: Write the code in Controller like this using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace WebApplication7.Controllers { public class HomeController : Controller { // GET: Home public ViewResult Index() { ViewData["Country"] = new List<string>() { "India", "Nepal", "US", "UK" }; return View(); } } }
Step 2: Write the code in View like this
@{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> <h2>Country List</h2> </head> <body> <div> <ul> @foreach (var strCountry in (List<string>) ViewData["Country"]) { <li> @strCountry </li> } </ul> </div> </body> </html>