1.

What is ViewBag and ViewData in ASP.NET MVC?

Answer»

ViewBag:

  • It is a Wrapper developed around ViewData and is a dynamic property that uses dynamic features of C# 4.0.
  • ViewBag is mainly used for the passing of value from the Controller to View where it does not require to Type Caste the data during data retrieval.
  • This ViewBag is available only for the Current Request and will be DESTRUCTED on re-direction.
  • Example:
    In the below given example, a string value will be set by the ViewBag object in Controller and later it will be displayed with the help of View.

Controller:

public CLASS ExampleController : Controller{ public ActionResult Index() { ViewBag.Message = "This is about ViewBag ASP.NET MVC!!"; return View(); }}

 View:

<html><head> <meta name="viewport" content="width=device-width"/> <title>IndexDisplay</title></head><body> <div> @ViewBag.Message </div></body></html>

ViewData:

  • It is derived from the class ViewDataDictionary and is originally a Dictionary object, which means it has Keys and Values where Keys represents the String and Values will be objects. Data will be stored in the form of Objects in ViewData.
  • ViewData is mainly used for the passing of value from the Controller to View. During retrieval of data, it needs to typecast the data into its ORIGINAL type since the data will be stored in the form of objects and it also needs NULL checks during data retrieval.
  • Similar to viewBag, this viewData is available only for Current Request and will be destructed upon redirection.
  • Example:
    In the below-given code, a string value will be set by the ViewData object in the Controller and later it will be displayed by the View.

Controller:

public class ExampleController : Controller{ public ActionResult Index() { ViewData["Message"] = "This is about ViewData in ASP.NET MVC!!!"; return View(); }}

  View:

<html><head> <meta name="viewport" content="width=device-width"/> <title>Index</title></head><body> <div> @ViewData["Message"] </div></body></html>


Discussion

No Comment Found