Why do we need MVC

Access model data using a controller

  • 3 minutes to read

by Scott Hanselman

This is a beginner tutorial that introduces the basics of ASP.NET MVC. You create a simple web application that reads and writes data to a database. Visit the ASP.NET MVC Learning Center for more ASP.NET MVC tutorials and samples.

In this section, we'll create a new moviescontroller class and write code to get the movie data and display it back in the browser using a viewing template.

Right click the Controllers folder and create a new moviescontroller.

Add controller

This will create a new "MoviesController.cs" file under our "\ controllers" folder in our project. Update the "" of "" to get the list of movies from our newly populated database.

We're running a LINQ query to only get movies released after the summer of 1984. We need a viewing template to restore the list of movies. So right click the method and select Add View to create it.

In the Add View dialog box, we indicate that we have a list of passed to our view template. Unlike the previous times, we used the Add View dialog box and created a "blank" template. in this case we specify that Visual Studio should automatically create a view template for us with a standard content. To do this, select the list element in the "Show content" drop-down menu.

Note that if you have created a new class, you must compile the application in order for it to appear in the Add View Box dialog.

When you click Add, the system will automatically generate the code for us to have a view showing the list of movies. Now is a good time to change the heading in "My Movie List", as you did earlier in the Hello World view.

Run the application and visit / Movies from the address bar. Now, with a simple query inside the controller, we pulled data from the database and returned the data to a view that knows about movies. That view then iterates down the list of movies and creates a table of dates for us.

The "Edit", "Details" and "Delete" functions are not implemented with this application. Therefore we do not need the standard shortcuts that were created for us by the scaffolding template. Open the / Movies / Index.aspx file and remove it.

The following is the source code for what our updated view template should look like after we made these changes:

It creates links that we don't need, so we'll delete them for this example. However, we reserve the right to use the new link "create new". This is the next step. This is what our app looks like with this column removed.

We now have a simple listing of our movie dates. However, when we click the "Create New" link, we get an error message because it is not linked. We implement a Create Action method and allow a user to enter new movies into the database.