What is ViewData in ASP .Net MVC C#?

CsharpServer Side ProgrammingProgramming

ViewData is a dictionary of objects that are 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. ViewData only transfers data from controller to view, not vice-versa. It is 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 mis-spell the key names we wouldn't get any compile time error. We will get to know about the error only at runtime.

Controller

Example

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();
      }
   }
}

View

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

Output


raja
Published on 24-Sep-2020 11:34:31
Advertisements