ViewBag property in MVC


The ViewBag property is typed as dynamic, which means that there is no IntelliSense.
ViewBag is alias/alternative syntax for accessing the ViewData dictionary. The two following lines of code are equivalent:

ViewBag.Message = "My message";
ViewData["Message"] = "My message";

ViewBag offers a slightly terser syntax than ViewData. Also notice that accessing ViewData using string keys also provides no IntelliSense, so you don't really lose any functionality.

One last note is that ViewBag and ViewData use the same backing storage, so that setting a property using one method makes it available using the other method:

ViewBag.Message = "My message";
string message = ViewData["Message"];

// message is now "My message"

Comments

  1. yes nice understanding abut Viewbag and ViewData

    Viewbag used the dynamic feature that was introduced in c#4.0 . It allows an object to have properties dynamically added it it so can we used this view bag with c# 3.5

    Both view bag and view data does not provide the compile time error for example mis spelles key or property name you would not get any compile time error , you get to know about error only at run time , Internaly view bag properties are stored as name/value pairs in the view data dictionary .
    so i thing it always good practice to use strongly typed models
    i m new in MVC if m wrong please correct me.
    thanks

    ReplyDelete

Post a Comment

Popular posts from this blog

Customize User's Profile in ASP.NET Identity System

Migrating database from ASP.NET Identity to ASP.NET Core Identity