Home  >  Article  >  Backend Development  >  What is ViewData in ASP .Net MVC C#?

What is ViewData in ASP .Net MVC C#?

PHPz
PHPzforward
2023-08-27 10:37:05967browse

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.

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

ASP .Net MVC C# 中的 ViewData 是什么?

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete