ViewBag :- ViewBag is a Dynamic Property of Controller Class that is used for sending small amount of temporary data from Contoller to View. Controller may have so many Action methods but ViewBag can only send data to views of respective action methods where the ViewBag property is used.
ViewBag 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. ViewBag is not required any kind of typecasting.
Note :- ViewBag can send data from Controller to View only and it is not possible to send data from View to Controller using the ViewBag. After the Redirection value of ViewBag always be null.
public class TestController : Controller
{ private readonly AppDbContext db;
public TestController(AppDbContext _db)
{
db = _db;
}
public IActionResult Index()
{
var dropdownItems = db.tblCountries.ToList();
ViewBag.Topictitle = "ViewBag Demo";
ViewBag.TotalRecordsCount = dropdownItems.Count;
ViewBag.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 Index action method. In the Index 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 viewbag proerty to store these data. Apart from it I have created two different ViewBag properties 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 Index method as shown in below image.
I have attached a screen image above in which you can see , I have retrieved the ViewBag data and used into heading tag. For retrieving the ViewBag values I have used ViewBag.Topictitle, ViewBag.TotalRecordsCount and ViewBag.Country without the typecasting of variable types. In ViewBag there is no need of Typecasting 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.
No need to do TypeCasting for retrieving the data from ViewBag as shown 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.