ViewBag & ViewData Asp.Net MVC

Discussion in 'ASP.NET' started by Sagar Jaybhay, Mar 3, 2020.

  1. Sagar Jaybhay

    Sagar Jaybhay New Member

    Joined:
    Jan 28, 2019
    Messages:
    29
    Likes Received:
    17
    Trophy Points:
    3
    Gender:
    Male
    Occupation:
    Sr. Software Developer
    Location:
    Pune
    Home Page:
    https://sagarjaybhay.net
    In this article we will under stand How to Pass Data From Controller to View.

    How to Pass Data From Controller to View using ViewBag and ViewData?

    ViewBag and ViewData In Asp.Net MVC.png

    Both are used to pass data from controller to view.


    ViewData is a dictionary of objects which store and retrieve the data based on key.

    Code:
    ViewData["Today"] = DateTime.Now;
    
    ViewBag uses the dynamic keyword internally and the dynamic keyword is introduced in C# v4. It allows objects to add as properties.

    Code:
    ViewBag.list = list;
    
    In this, both do not provide compile-time error checking. Means if given ABC as a key name in the controller and in view if you misspell Abc then it will not provide compile-time checking. You will get the error at runtime only. It is good practice to pass data from controller to view using a strongly typed model.

    ViewBag is a sugar coating over ViewData. Internally ViewBag properties are stored name-value pair list.


     
    shabbir likes this.

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice