Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What is ViewData in ASP .Net MVC C#?
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

Advertisements