Pass data to index view
Passing data from controller to view
Currently our MoviesController
has just boiler-plate code. Let us modify it's Index
action to send the data we from context to the corresponding view
Modify the MoviesController
as shown below:
We created an instance of the FakeContext
class and returned its Movie
property to the view in line 14. Ideally it must have been Movies and
not Movie
Note the following
The ActionResult
type that the Index method is returning is the default implementation of IActionResult
Interface. This is standard interface which defines how and what data can be sent to the view.
The methods View
() and Problem
() are inherited from Controller
base class! Using these methods, we can pass data object or errors which will then be used by the view.
The controller currently has a dependency on the FakeContext class. This a violation of loose coupling principle. We will later see how we can inject this dependency into the controller at runtime.
Run the app
Run the app now and change the url to:
When the browser sends this request, the controller tries to match this pattern to MoviesController's Index
() method using the basic routing feature, based on conventions! The method then fetches data from the context object and passes it over to the view
The view code (in Index.cshtml) loops over the Model collection received from the controller and generates the html content which is then sent back to the browser!
This is a get
request in action and we will see other actions also next.
Last updated