ViewData :- ViewData is a Dynamic Property of ControllerBase Class that is used for sending data from Contoller to View. It is a Dictionary object having key value pair. Key is the name of ViewData and value is the stored data into it. Controller may have so many Action methods but ViewBag can only send data to views of respective action methods where the ViewData property is used.
ViewData do not have a Compile Time error checking mechanism because it uses the dynamic types like var in C# that decided the type at run time and accroding to data it will work. ViewData is required typecasting for different types of data stored into it. There is no any typecasting required for String data other than string it is required the typecasting.
Note :- ViewData can send data from Controller to View only and it is not possible to send data from View to Controller using the ViewData. After the Redirection value of ViewData always be null it is valid only for single HTTP request.
public class TestController : Controller
{ private readonly AppDbContext db;
public TestController(AppDbContext _db)
{
db = _db;
}
public IActionResult ViewDataExample()
{
var dropdownItems = db.tblCountries.ToList();
ViewData["Topictitle"] = "ViewData Example";
iewData["TotalRecordsCount"] = dropdownItems.Count;
ViewData["Country"] = new SelectList
(dropdownItems, "CountryId", "CountryName");
return View();
}
}
I have attached a screen image above in which you can see , I have created a Test Controller and inside the Test Controller I created a ViewDataExample action method. In the ViewDataExample method I have fetched country records from tblCountries table in SQL Database and assigned it to a variable. After that I used a Country dynamic ViewData key to store these data. Apart from it I have created two different ViewData keys that is Topictitle used for storing the topic title and second one is TotalRecordsCount for storing the number of records in dropdownlist. Now create a View for ViewDataExample method as shown in below image.
I have attached a screen image above in which you can see , I have retrieved the ViewData data and used into heading tag. For retrieving the ViewData values I have used ViewData["Topictitle"], ViewData["TotalRecordsCount"] and "var country = ViewData["Country"] as SelectList;" with the typecasting of SelectList types. In ViewData there is a need of Typecasting for data based on whether it holds string data or any other complex types like a list or object. Run the application and you can see the final output as like as in below image.
About the Author
Sudheer Singh Chouhan is a Software Engineer having Expertise in Development Design and Architecting the
applications , Project Management , Designing Large Scale Databases in SQL Server since last 17 Years.
Skill Sets :- Microsoft .NET technologies like ASP.Net Core, Web API, LINQ, Web Forms, WinForms, SQL Server,
EntityFramework, Design Patterns, Solid Principles, Microservices, AWS Cloud.