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:

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MvcMovie.Data;

namespace MvcMovie.Controllers
{
    public class MoviesController : Controller
    {
        FakeContext _context;
        // GET: MoviesController
        public ActionResult Index()
        {
            _context= new FakeContext();
            return _context.Movie != null ?
                View(_context.Movie) :
                Problem("Movie list is null.");
        }
        
       //other code...
    }
}

We created an instance of the FakeContextclass and returned its Movieproperty to the view in line 14. Ideally it must have been Movies and not Movie

Note the following

The ActionResulttype 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:

//port number may vary
//the /index is also optional

https://localhost:7161/movies/index

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