Cristopher Coronado
What is the difference between ViewData and ViewBag in ASP.NET MVC?
By Cristopher Coronado in .NET Core on Mar 22 2023
  • Jay Pankhaniya
    Apr, 2023 14

    ViewData and ViewBag are two techniques that allow passing data from controllers to views in ASP.NET MVC.

    ViewData is a dictionary object that allows passing data as key-value pairs between the controller and the view. It is a property of the base class Controller and can be used to store and retrieve data in the same controller action. However, it has the limitation of being strongly typed, meaning that the key and value must be explicitly cast when retrieved in the view.

    On the other hand, ViewBag is a dynamic object that allows passing data as properties from the controller to the view. Unlike ViewData, ViewBag is not type-safe, which means it does not require explicit casting to retrieve data in the view.

    1. //ViewData
    2. public ActionResult Index()
    3. {
    4. ViewData["Message"] = "Hello, world!";
    5. return View();
    6. }
    7. //ViewBag
    8. public ActionResult Index()
    9. {
    10. ViewBag.Message = "Hello, world!";
    11. return View();
    12. }
    13. //In View
    14. <h1>@ViewData["Message"]</h1>
    15. <h1>@ViewBag.Message</h1>

    In general, ViewBag is easier to use but can be more error-prone than ViewData, as there is no compile-time checking. Therefore, it is recommended to use ViewData for strongly typed data and ViewBag for dynamic data.

    • 1
  • Sagar Malde
    Mar, 2023 31

Most Popular Job Functions