#64 ViewData and ViewBag

They are responsible for passing data from controller to view.

ViewData:

1.It is a dictionary,which holds keys as strings.

2.It can be used to store any complex data.

3.They have to casted/Null check has to be made in view to avoid Error.

ViewBag:

1.They use dynamic property listed with C#4.0

2.They do not require type casting of complex objects.


/*Controller*/

public ActionResult Index()
{
ViewData["Sample"] = "Sample ViewData";
ViewBag.Hello = "Sample ViewBag";
return View();
}

They are accessed in view with respective Name declared in controller

/*View*/

@ViewBag.Hello
@ViewData["Sample"]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s