- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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
- Related Articles
- What is the significance of NonActionAttribute in ASP .Net MVC C#?
- What is the use of ChildActionOnly attribute in ASP .Net MVC C#?
- How to use ViewBag in ASP .Net MVC C#?
- What are the levels at which filters can be applied in ASP .Net MVC C#?
- What are the three segments of the default route, that is present in ASP .Net MVC C#?
- How can we provide an alias name for an action method in Asp .Net MVC C#?
- What is serialization in C#.NET?
- What are access specifiers in C#.NET?
- What is net investment hedge?
- What is the base class for all data types in C#.NET?
- What is Net Working Capital Ratio?
- What are the different access specifiers in C#.NET?
- What is Net Working Capital (NWC) Flow?
- What is Net Concept of Working Capital?
- What is the formula of net displacement?

Advertisements