AspBucket offers ASP.NET, C#, VB, Jquery, CSS, Ajax, SQL tutorials. It is the best place for programmers to learn

Monday 5 October 2015

ViewBag, ViewData, and ViewDataDictionary in MVC

Lets discuss about the ViewBag to pass information from the controller to the view and then moved to passing a strongly typed model. In reality, both these values are passed via theViewDataDictionary. Let’s look at that in more detail.

Technically, all data is passed from the controllers to the views via a ViewDataDictionary (a specialized dictionary class) called ViewData. You can set and read values to the ViewData dictionary using standard dictionary syntax, as follows:

ViewData["CurrentTime"] = DateTime.Now;

Although this continues to be available, ASP.NET MVC 3 leveraged the C# 4 dynamic keyword to allow for a simpler syntax. The ViewBag is a dynamic wrapper around ViewData. It allows you to set values as follows:
Thus, ViewBag.CurrentTime is equivalent to ViewData["CurrentTime"].

Generally, most current code you’ll encounter uses ViewBag rather than ViewData. For the most part, you don’t have a real technical advantage when choosing one syntax over the other. ViewBag is just syntactic sugar that some people prefer over the dictionary syntax. It just looks nicer.


Post a Comment

  • Popular Posts
  • Comments