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

What is ViewData in ASP .Net MVC C#?

PHPz
Release: 2023-08-27 10:37:05
forward
1018 people have browsed it

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;
Copy after login

Retrieving data from ViewData-

string country = ViewData["MyCountry"].ToString();
Copy after login

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

View

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

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template