Sample Site Repo
Server Side Technologies need to be able to send data from the Controller (often prescribed by the Model) to the View. This document outlines the core techniques available.
This document references a Repo found on GitHub at:
Supporting Video: Sending Data from the Controller to the View in asp.net MVC
ViewBag
ViewBag enables sharing of values dynamically between the Controller and View.
Values declared in The Controller as ViewBag.Greeting = "String" can be displayed in the view with the Razor Expression @ViewBag.Greeting
You can assign any number of properties and values to ViewBag and these can be primitives or complex objects.
In the sample files locate Controllers/DataExamplesController.cs and the Action ViewBagDemo().
The ViewBag value can then be displayed in the View.
In the sample files locate Views/DataExamples/ViewBagDemo.cshtml which outputs the ViewBag() values.
ViewData
ViewData also enables sharing of values dynamically between the Controller and View.
Unlike ViewBag, with ViewData values must be typecast to an appropriate type before using it.
Values declared in The Controller as ViewData["Greeting"] can be displayed in the view with the Razor Expression @ViewData.Greeting.
You can assign any number of properties and values to ViewData and these can be primitive or complex object.
In the sample files locate Controllers/DataExamplesController.cs and the Action ViewDataDemo().
The ViewData value can then be displayed in the View.
In the sample files locate Views/DataExamples/ViewDataDemo.cshtml which outputs the ViewData() values.
ViewBag internally inserts data into ViewData dictionary. As such the key of ViewData and property of ViewBag must NOT match.
Models
ViewBag and ViewData are equally valid approaches for passing small amounts of data from controllers to views.
However, a more robust way to send data to the view is via a Model known as a viewmodel.
This is the technique used for Database transactions.
This technique needs a Model to be declared. In the sample file locate Models/Book.cs which illustrates a Model defined as a Class.
In the Controllers/DataExamplesController.cs an object based on this model is created and then passed to the View directly through View(model).
In the View Views/DataExamples/ModelDemo.cshtml specify a model using the @model directive ie @model YourAppName.Models.Book.
Values from the the model can then be referenced with @Model ie Model.BookTitle.