Accessing Your Model's Data from a Controller

4.38 (8 votes)

This tutorial is the sixth in a series of a Visual Basic versions of the Introduction to ASP.NET MVC 5 tutorials published on the www.asp.net site. The original series, produced by Scott Guthrie (twitter @scottgu ), Scott Hanselman (twitter: @shanselman ), and Rick Anderson ( @RickAndMSFT ) was written using the C# language. My versions keep as close to the originals as possible, changing only the coding language. The narrative text is largely unchanged from the original and is used with permission from Microsoft.

This tutorial series will teach you the basics of building an ASP.NET MVC 5 Web application using Visual Studio 2013 and Visual Basic.  A Visual Studio Express For Web project with VB source code is available to accompany this series which you can download.

The tutorial series comprises 11 sections in total. They cover the basics of web development using the ASP.NET MVC framework and the Entity Framework for data access. They are intended to be followed sequentially as each section builds on the knowledge imparted in the previous sections. The navigation path through the series is as follows:

  1. Getting Started
  2. Adding a Controller
  3. Adding a View
  4. Adding a Model
  5. Creating a Connection String and Working with SQL Server LocalDB
  6. Accessing Your Model's Data from a Controller
  7. Examining the Edit Methods and Edit View
  8. Adding Search
  9. Adding a New Field
  10. Adding Validation
  11. Examining the Details and Delete Methods

6. Accessing Your Model's Data from a Controller

In this section, you'll create a new MoviesController class and write code that retrieves movie data and displays it in the browser using a view template.

Build the application (press Ctrl+Shift+B, or select 'Build MvcMovie' from the Debug menu, or right click on the project name in Solution Explorer and select 'Build') before going on to the next step. If  you don't build the application, you'll get an error when adding a controller.

In Solution Explorer, right-click the Controllers folder and then  click Add, then Controller.

Accessing Model

 

In the Add Scaffold dialog box, click MVC 5  Controller with views, using Entity Framework, and then click Add.

Accessing Model

 

    • For the Controller name enter MoviesController.
    • Select  Movie (MvcMovie.Models)  for the Model class.
    • Select MovieDBContext (MvcMovie.Models) for the Data context class.

The image below shows the completed dialog.

Accessing Model

Click Add. (If you get an error, you probably didn't build the application before starting adding the controller.) Visual Studio creates the following files and folders:

  • A MoviesController.vb file in the Controllers folder.
  • Views\Movies folder.
  • Create.vbhtml, Delete.vbhtml, Details.vbhtml, Edit.vbhtml, and Index.vbhtml in the new Views\Movies folder.

Visual Studio automatically created the CRUD (Create, Read, Update, and Delete) action methods and views for you (the automatic creation of CRUD action methods and views is known as scaffolding). You now have a fully functional web application that lets you create, list, edit, and delete movie entries.

Run the application and click on the MVC Movie link (or browse to the Movies controller by appending /Movies to the URL in the address bar of your browser).  Because the application relies on the default routing (defined in the App_Start\RouteConfig.vb file), the browser request http://localhost:xxxxx/Movies is routed to the default Index action method of the Movies controller. In other words, the browser request http://localhost:xxxxx/Movies  is effectively the same as the browser request http://localhost:xxxxx/Movies/Index. The result is an empty list of movies, because you haven't added any yet.

Accessing Model

Creating a Movie

Select the Create New link. Enter some details about a movie and then click the Create button.

Accessing Model

Note: Depending on your regional settings, you may not be able to enter decimal points or commas in the Price field. To support jQuery validation for non-English locales that use a comma (",") for a decimal point, and non US-English date formats, you must include globalize.js and your specific cultures/globalize.cultures.js file (from https://github.com/jquery/globalize ) and JavaScript to use Globalize.parseFloat. I'll show how to do this in the next tutorial. For now, just enter whole numbers like 10.

Clicking the Create button causes the form to be posted to the server, where the movie information is saved to the database. You're then redirected to the /Movies URL, where you can see the newly created movie in the listing.

Accessing Model

Create a couple more movie entries. Try the EditDetails, and Delete links, which are all functional.

Examining the Generated Code

Open the Controllers\MoviesController.vb file and examine the generated Index method. A portion of the movie controller with the Index method is shown below.

Namespace MvcMovie
    Public Class MoviesController
        Inherits System.Web.Mvc.Controller

        Private db As New MovieDbContext

        ' GET: /Movies/
        Function Index() As ActionResult
            Return View(db.Movies.ToList())
        End Function

A request to the Movies controller returns all the entries in the Movies table and then passes the results to the Index view. The following line from the MoviesController class instantiates a movie database context, as described previously. You can use the movie database context to query, edit, and delete movies.

Private db As New MovieDbContext

Strongly Typed Models and the @ModelType Keyword

Earlier in this tutorial, you saw how a controller can pass data or objects to a view template using the ViewBag object. The ViewBag  is a dynamic object that provides a convenient late-bound way to pass information to a view.

MVC also provides the ability to pass strongly typed objects to a view template. This strongly typed approach enables better compile-time checking of your code and richer IntelliSense in the Visual Studio editor. The scaffolding mechanism in Visual Studio used this approach (that is, passing a  strongly typed model) with the MoviesController class and view templates when it created the methods and views.

In the Controllers\MoviesController.vb file examine the generated Details method.  The Details method is shown below.

' GET: /Movies/Details/5
Function Details(ByVal id As Integer?) As ActionResult
    If IsNothing(id) Then
        Return New HttpStatusCodeResult(HttpStatusCode.BadRequest)
    End If
    Dim movie As Movie = db.Movies.Find(id)
    If IsNothing(movie) Then
        Return HttpNotFound()
    End If
    Return View(movie)
End Function

The id parameter is generally passed as route data, for example http://localhost:1234/movies/details/1 will set the controller to the movie controller, the action to details and the id to 1. You could also pass in the id with a query string as follows:

http://localhost:1234/movies/details?id=1

If a  Movie is found, an instance of the Movie model is passed to the Details view:

Return View(movie)

Examine the contents of the Views\Movies\Details.vbhtml file:

@ModelType MvcMovie.Models.Movie
@Code
    ViewData("Title") = "Details"
End Code

<h2>Details</h2>

<div>
    <h4>Movie</h4>
    <hr />
    <dl class="dl-horizontal">
        <dt>
            @Html.DisplayNameFor(Function(model) model.Title)
        </dt>

        @*Markup omitted for clarity*@

    </dl>
</div>
<p>
    @Html.ActionLink("Edit", "Edit", New With { .id = Model.ID }) |
    @Html.ActionLink("Back to List", "Index")
</p>

By including a @ModelType statement at the top of the view template file, you can specify the type of object that the view expects. When you created the movie controller, Visual Studio automatically included the following @ModelType statement at the top of the Details.vbhtml file based on the Model class you selected when adding the controller:

@ModelType MvcMovie.Models.Movie

This @ModelType directive allows you to access the movie that the controller passed to the view by using a Model object that's strongly typed. For example, in the Details.vbhtml template, the code passes each movie field to the DisplayNameFor and DisplayFor HTML Helpers with the strongly typed Model object.  The Create and  Edit methods and  view templates also pass a movie model object.

Examine the Index.vbhtml view template and the Index method in the MoviesController.vb file. Notice how the code creates a List object when it calls the View helper method in the Index action method. The code then passes this Movies list from the Index action method to the view:

Function Index() As ActionResult 
    Return View(db.Movies.ToList())
End Function

When you created the movie controller, Visual Studio automatically included the following @ModelType statement at the top of the Index.cshtml file:

@ModelType IEnumerable(Of MvcMovie.Models.Movie)

This @ModelType directive allows you to access the list of movies that the controller passed to the view by using a Model object that's strongly typed. For example, in the Index.vbhtml template, the code loops through the movies by doing a For Each statement over the strongly typed Model object:

@For Each item In Model
    @<tr>
        <td>
            @Html.DisplayFor(Function(modelItem) item.Title)
        </td>
        <td>
            @Html.DisplayFor(Function(modelItem) item.ReleaseDate)
        </td>
        <td>
            @Html.DisplayFor(Function(modelItem) item.Genre)
        </td>
        <td>
            @Html.DisplayFor(Function(modelItem) item.Price)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", New With {.id = item.ID }) |
            @Html.ActionLink("Details", "Details", New With {.id = item.ID }) |
            @Html.ActionLink("Delete", "Delete", New With {.id = item.ID })
        </td>
    </tr>
Next

Because the Model object is strongly typed (as an IEnumerable<Movie> object in this example), each item object in the loop is typed as Movie. Among other benefits, this means that you get  compile-time checking of the code and full IntelliSense support in the code editor:

Accessing Model

Working with SQL Server LocalDB

Entity Framework Code First detected that the database connection string that was provided pointed to a Movies database that didn’t exist yet, so Code First created the database automatically. You can verify that it's been created by looking in the App_Data folder. If you don't see the Movies.mdf file, click the Show All Files button in the Solution Explorer toolbar, click the Refresh  button, and then expand the App_Data folder.

Accessing Model

Double-click Movies.mdf to open SERVER EXPLORER, then expand the Tables folder to see the Movies table. Note the key icon next to ID. By default, EF will make a property named ID the primary key. For more information on EF and MVC, see this tutorial series on MVC and EF.

Accessing Model

 

Right-click the Movies table and select Show Table Data  to see the data you created.

Accessing Model

Accessing Model

 

Right-click the Movies table and select Open Table Definition to see the table structure that Entity Framework Code First created for you.

Accessing Model

Accessing Model

Notice how the schema of the Movies table maps to the Movie class you created earlier. Entity Framework Code First automatically created this schema for you based on your Movie class.

When you're finished, close the connection by right clicking MovieDBContext and selecting Close Connection. (If you don't close the connection, you might get an error the next time you run the project).

Accessing Model

You now have a database and pages to display, edit, update and delete data. In the next tutorial, we'll examine the rest of the scaffolded code and add  a SearchIndex method and a SearchIndex view that lets you search for movies in this database. For more information on using Entity Framework with MVC, see Creating an Entity Framework Data Model for an ASP.NET MVC Application.

 

You might also like...

Date Posted:
Last Updated:
Posted by:
Total Views to date: 50019

13 Comments

- Arnie

I already build the application but still I got an error. Please answer me, because I want to learn more about MVC.

- mike

@Arnie,

Post a question about your issue to http://forums.asp.net or http://stackoverflow.com. When you do, make sure you explain what you did, what error you get and what line of code causes the error. Otherwise no one will be able to help you.

- Gjuro

The article mentions "Creating an Entity Framework Data Model for an ASP.NET MVC Application" tutorial (at http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application) which is a C# version of it, and you failed to mention your own VB.NET version of it (at www.mikesdotnetting.com/article/241/mvc-5-with-ef-6-in-visual-basic-creating-an-entity-framework-data-model). Visitors of this page are obviously VB users, and would probably be more interested in your VB version of that EF6 tutorial. :-)

- Mike

@Gjuro

Thanks for pointing that out.

- Biplab

Its very cool !!! simply the best tutorial.

- KrASh

Hello, I'm following the tutorial but getting a problem here. I built the application like you said but when I try to add a controler the dialog its diff. I can choose the model class but for Data context class I can only choose applicationDbContext, theres a + button where I can write other name, i wrote the MovieDbContext but at the end, when I create I got an error saying it cant find metadata and the class has no primary key, I've tried the <key> before the id property but still getting the error. I've read around that people with this problem its related to connection string, is there any chance to check its connecting to the server or you have any idea how to fix it? thanks

- Mike

@KrAsh

Download the code sample for this tutorial series( link at the top of the page just under the advert banner) and review the code there to see how it compares to yours.

- Luis

Hi.

Great tutorial. I'm starting to learn MVC.

What can I do for when the Create Button is clicked it saves the data and gets back to the Create page instead of the updated list.

Thanks

- Luis

Ok. I got it!
Return RedirectToAction("Create")
on the controller :-)
thanks

- KrASh

Thanks, I had some silly mistake, can't remember now what it was (had some personal problems last week) but i got to solve the problem. Thanks. Its a shame almost everything its in C# about MVC, i was really thinking about learn it because it was frustrating not to find some stuff in vb.net. Thanks again for your help

- Peter

How i can change view label from "ReleaseDate" to "Release Date". Just the name of the field.

- Mike

@Peter,

That's covered in the next tutorial in the series. You use DataAnnotation attributes to change what's displayed in labels:

<Display(Name:="Release Date")>


You decorate the relevant property's name with that attribute:

<Display(Name:="Release Date")>

Public Property ReleaseDate As DateTime

- Peter

Thanks.Got it.

Recent Comments

ojorma 17/06/2017 09:24
In response to Razor Pages - The Elevator Pitch
Finally I can say goodbye to webforms...

Mau 06/06/2017 08:58
In response to Razor Pages - The Elevator Pitch
I am missing the razor view code. Thank you for your article. Design pattern should improve the of...

Obinna Okafor 26/05/2017 16:16
In response to Razor Pages - The Elevator Pitch
Thank you for this wonderful piece, Mike. I need more of these...Keep them coming - anything more...

Cyrus 26/05/2017 06:00
In response to Razor Pages - The Elevator Pitch
There are some concern about razor pages performance. Is it faster or slower than MVC? would you a a...

Cyrus 26/05/2017 05:44
In response to Razor Pages - Understanding Handler Methods
well done, thank you....

Satyabrata Mohapatra 23/05/2017 11:41
In response to Razor Pages - Understanding Handler Methods
Nice and easy !! Great post....

Cyrus 16/05/2017 19:55
In response to Razor Pages - Getting Started With The Preview
There is something wrong related to microsoft.dotnetcore.mvc.taghelpers! if you remove it from page...

Cyrus 16/05/2017 10:18
In response to Razor Pages - Getting Started With The Preview
well done mike, it was very useful, I really appreciate that....

Satyabrata Mohapatra 16/05/2017 07:21
In response to Razor Pages - Getting Started With The Preview
Finally!!!! web pages in asp.net core!!! Super excited !!!! Thank u sir for sharing.....Awaiting on...

Daniele 14/03/2017 10:24
In response to Working With Zip Files In ASP.NET MVC
is it possible give to the user a progress bar of the zipping process? Thanks in advance. ...