Upload
lukas-martinelli
View
220
Download
0
Embed Size (px)
DESCRIPTION
MVC 3 Example etc etc...
Citation preview
Tutorial of the Movie Database Application in MVC 3
Our simple Movie Database application will allow us to do three things:
1. List a set of movie database records
2. Create a new movie database record 3. Edit an existing movie database record
In order to create our application, we need to complete each of the following steps:
1. Create the ASP.NET MVC 3 Web Application Project
2. Create the database
3. Create the database model
4. Create the ASP.NET MVC controller 5. Create the ASP.NET MVC views
Creating an ASP.NET MVC 3 Web Application Project
Let's start by creating a new ASP.NET MVC 3 Web Application project in Visual Studio 2010.
Select the menu option File, New Project and you will see the New Project dialog box in Figure
1. Select C# as the programming language and select the ASP.NET MVC 3 Web Application
project template. Give your project the name MovieApp and click the OK button.
Figure 1
Whenever you create a new MVC 3 Web Application project, Visual Studio prompts you to create
a separate unit test project. The dialog in Figure 2 appears. Because we won't be creating tests
in this tutorial because of time constraints (and, yes, we should feel a little guilty about this)
uncheck the option „Create a unit test project“ and click the OK button.
Figure 2
An ASP.NET MVC application has a standard set of folders: a Models, Views, and Controllers
folder. You can see this standard set of folders in the Solution Explorer window. We'll need to
add files to each of the Models, Views, and Controllers folders in order to build our Movie Database application.
When you create a new MVC application with Visual Studio, you get a sample application.
Because we want to start from scratch, we need to delete the content for this sample
application. You need to delete the following file and the following folder:
Controllers\HomeController.cs Views\Home
Creating the Database
We need to create a database to hold our movie database records. Follow these steps to create the database:
1. Right-click the App_Data folder in the Solution Explorer window and select the menu
option Add, New Item.
2. Select the Data category and select the SQL Server Database template (see Figure 3). 3. Name your new database MoviesDB.mdf and click the Add button.
Figure 3
After you create your database, you can connect to the database by double-clicking the
MoviesDB.mdf file located in the App_Data folder. Double-clicking the MoviesDB.mdf file opens the Server Explorer window.
Next, we need to create a new database table. From within the Sever Explorer window, right-click
the Tables folder and select the menu option Add New Table. Selecting this menu option opens the database table designer. Create the following database columns:
Column Name Data Type Allow Nulls
Id Int False
Title Nvarchar(100) False
Director Nvarchar(100) False
DateReleased DateTime False
The first column, the Id column, has two special properties. First, you need to mark the Id
column as the primary key column. After selecting the Id column, right-click and choose Set
Primary Key button (it is the icon that looks like a key). Second, you need to mark the Id
column as an Identity column. In the Column Properties window, scroll down to the Identity
Specification section and expand it. Change the Is Identity property to the value Yes. When you are finished, the table should look like Figure 4.
Figure 4
The final step is to save the new table. Click the Save button (the icon of the floppy) and give
the new table the name Movies.
After you finish creating the table, add some movie records to the table. Right-click the Movies
table in the Server Explorer window and select the menu option Show Table Data. Enter a list of your favorite movies (see Figure 5).
Figure 5
Creating the Model
We next need to create a set of classes to represent our database. We need to create a database
model. We'll take advantage of the Microsoft Entity Framework to generate the classes for our database model automatically.
Follow these steps to launch the Entity Data Model Wizard:
1. Right-click the Models folder in the Solution Explorer window and the select the menu
option Add, New Item.
2. Select the Data category and select the ADO.NET Entity Data Model template. 3. Give your data model the name MoviesDBModel.edmx and click the Add button.
After you click the Add button, the Entity Data Model Wizard appears (see Figure 6). Follow these steps to complete the wizard:
1. In the Choose Model Contents step, select the Generate from database option.
2. In the Choose Your Data Connection step, use the MoviesDB.mdf data connection and the
name MoviesDBEntities for the connection settings. Click the Next button.
3. In the Choose Your Database Objects step, expand the Tables node, select the Movies
table. Enter the namespace MovieApp.Models and click the Finish button.
Figure 6
After you complete the Entity Data Model Wizard, the Entity Data Model Designer opens. The
Designer should display the Movies database table (see Figure 7).
Figure 7
We need to make one change before we continue. The Entity Data Wizard generates a model
class named Movies that represents the Movies database table. Because we'll use the Movies
class to represent a particular movie, we need to modify the name of the class to be Movie instead of Movies (singular rather than plural).
Double-click the name of the class on the designer surface and change the name of the class
from Movies to Movie. After making this change, click the Save button (the icon of the floppy
disk) to generate the Movie class.
Creating the ASP.NET MVC Controller
The next step is to create the ASP.NET MVC controller. A controller is responsible for controlling
how a user interacts with an ASP.NET MVC application.
Follow these steps:
1. In the Solution Explorer window, right-click the Controllers folder and select the menu
option Add, Controller.
2. In the Add Controller dialog, enter the name HomeController and check Add action
methods for Create, Update, Delete and Details scenarios (see Figure 8). 3. Click the Add button to add the new controller to your project.
Figure 8
After you complete these steps, the controller HomeController is created. Notice that it contains
methods named Index, Details, Create, Edit and Delete. In the following sections, we'll add the necessary code to get some of these methods to work.
Listing Database Records
The Index() method of the Home controller is the default method for an ASP.NET MVC application.
When you run an ASP.NET MVC application, the Index() method is the first controller method that is called.
We'll use the Index() method to display the list of records from the Movies database table.
I've modified the HomeController class in Listing 1 so that it contains a new private field named _db.
The MoviesDBEntities class represents our database model and we'll use this class to communicate with our database.
I've also modified the Index() method in Listing 1. The Index() method uses the MoviesDBEntities
class to retrieve all of the movie records from the Movies database table. The
expression _db.Movies.ToList() returns a list of all of the movie records from the Movies database table.
using System.Linq; using System.Web.Mvc; using MovieApp.Models; namespace MovieApp.Controllers { public class HomeController : Controller { private MoviesDBEntities _db = new MoviesDBEntities(); // // GET: /Home/ public ActionResult Index() { return View(_db.Movies.ToList()); } } } Listing 1 - Controllers/HomeController.cs (modified Index method)
The Index() method returns a view named Index. We need to create this view to display the list
of movie database records. Follow these steps:
You should build your project (select the menu option Build, Build Solution) before opening the Add View dialog or no classes will appear in the View data class dropdown list.
1. Right-click the Index() method in the code editor and select the menu option Add
View (see Figure 9).
2. In the Add View dialog, verify that the checkbox labeled Create a strongly-typed
view is checked.
3. From the View content dropdown list, select the value List.
4. From the Scaffold template dropdown list, select the value Movie (MovieApp.Models).
5. Click the Add button to create the new view (see Figure 10).
After you complete these steps, a new view named Index.cshtml is added to the Views\Home folder.
Figure 9
Figure 10
The Index view displays all of the movie records from the Movies database table within a HTML
table. The view contains a foreach loop that iterates through each movie represented by the
ViewData.Model property. If you run your application by hitting the F5 key, then you'll see the
web page in Figure 11.
Figure 11
Creating New Database Records
The Index view that we created in the previous section includes a link for creating new database
records. Let's go ahead and implement the logic and create the view necessary for creating new
movie database records.
The Home controller contains two methods named Create(). The first Create() method has no
parameters. This overload of the Create() method is used to display the HTML form for creating a new movie database record.
The second Create() method has a FormCollection parameter. This overload of the Create()
method is called when the HTML form for creating a new movie is posted to the server. Notice
that this second Create() method has an [HttpPost] attribute that prevents the method from being called unless an HTTP POST operation is performed.
This second Create() method has been modified in the updated HomeController class in Listing
2. The new version of the Create() method accepts a Movie parameter and contains the logic for inserting a new movie into the Movies database table.
[HttpPost] public ActionResult Create(Movie newMovie) { if (!ModelState.IsValid) return View(); _db.AddToMovies(newMovie); _db.SaveChanges(); return RedirectToAction("Index"); } Listing 2 - Controllers/HomeController.cs (modified Create method)
Visual Studio makes it easy to create the form for creating a new movie database record (see Figure
12). Follow these steps:
1. Right-click the Create() method in the code editor and select the menu option Add View.
2. Verify that the checkbox labeled Create a strongly-typed view is checked.
3. From the View content dropdown list, select the value Create.
4. From the View data class dropdown list, select the value Movie (MovieApp.Models). 5. Click the Add button to create the new view.
Figure 12
After you add the Create view, you can add new Movie records to the database. Run your
application by pressing the F5 key and click the Create New link to see the form in Figure 13. If you complete and submit the form, a new movie database record is created.
Notice that you get form validation automatically. If you neglect to enter a release date for a
movie, or you enter an invalid release date, then the form is redisplayed and the release date field is highlighted.
Figure 13
Editing Existing Database Records
In this final section, we discuss how you can edit existing database records.
First, we need to generate the Edit form. This step is easy since Visual Studio will generate the
Edit form for us automatically. Open the HomeController.cs class in the Visual Studio code editor and follow these steps:
1. Right-click the Edit() method in the code editor and select the menu option Add View
2. Check the checkbox labeled Create a strongly-typed view.
3. From the View content dropdown list, select the value Edit.
4. From the View data class dropdown list, select the value Movie (MovieApp.Models). 5. Click the Add button to create the new view.
Completing these steps adds a new view named Edit.cshtml to the Views\Home folder. This view contains an HTML form for editing a movie record.
Finally, we need to modify the Home controller so that it supports editing a database record.
The updated HomeController class is contained in Listing 3.
public ActionResult Edit(int id) { var movieToEdit = (from m in _db.Movies where m.Id == id select m).First(); return View(movieToEdit); } [HttpPost] public ActionResult Edit(int id, Movie editMovie) { var originalMovie = (from m in _db.Movies where m.Id == editMovie.Id select m).First(); if (!ModelState.IsValid) return View(originalMovie); _db.ApplyCurrentValues(originalMovie.EntityKey.EntitySetName, editMovie); _db.SaveChanges(); return RedirectToAction("Index"); } Listing 3 - Controllers\HomeController.cs (Edit methods)
Summary
The purpose of this tutorial was to give you a sense of the experience of building an ASP.NET
MVC 3 application. I hope that you discovered that building an ASP.NET MVC 3 web application is very similar to the experience of building ASP.NET application.