ViewData is a dictionary of objects stored and retrieved using strings as keys. It is used to transfer data from controller to view. Since ViewData is a dictionary, it Contains key-value pairs, where each key must be a string. View data transfer only Data goes from controller to view and vice versa. Valid only during the current request.
Storing data in ViewData-
ViewData["countries"] = countriesList;
Retrieving data from ViewData-
string country = ViewData["MyCountry"].ToString();
ViewData does not provide compile-time error checking . For example, if we misspell keyname we won't get any compile time errors. we will learn about The error only occurs at runtime.
using System.Collections.Generic; using System.Web.Mvc; namespace DemoMvcApplication.Controllers{ public class HomeController : Controller{ public ViewResult Index(){ ViewData["Countries"] = new List<string>{ "India", "Malaysia", "Dubai", "USA", "UK" }; return View(); } } }
@{ ViewBag.Title = "Countries List"; } <h2>Countries List</h2> <ul> @foreach(string country in (List<string>)ViewData["Countries"]){ <li>@country</li> } </ul>
The above is the detailed content of What is ViewData in ASP .Net MVC C#?. For more information, please follow other related articles on the PHP Chinese website!