Part 1: File->New Project and Controllers

 

Part 1: File->New Project and Controllers

 
 

 

The MVC Music Store is a tutorial application that introduces and explains step-by-step how to use ASP.NET MVC and Visual Studio for web development.

The MVC Music Store is a lightweight sample store implementation which sells music albums online, and implements basic site administration, user sign-in, and shopping cart functionality.

This tutorial series details all of the steps taken to build the ASP.NET MVC Music Store sample application.  Part 1 covers Overview, File/New Project, and Controllers.

 

Download MVC Music Store application  |  Download complete tutorial in PDF format

 

Overview

This tutorial is an introduction to ASP.NET MVC 2. We'll be starting slowly, so beginner level web development experience is okay.

The application we'll be building is a simple music store. There are three main parts to the application: shopping, checkout, and administration.

Visitors can browse Albums by Genre:

They can view a single album and add it to their cart:

They can review their cart, removing any items they no longer want:

Proceeding to Checkout will prompt them to login or register for a user account.

After creating an account, they can complete the order by filling out shipping and payment information. To keep things simple, we're running an amazing promotion: everything's free if they enter promotion code "FREE"!

After ordering, they see a simple confirmation screen:

The Administration page shows a list of albums from which Administrators can Create, Edit, and Delete albums:

We'll begin by creating a new ASP.NET MVC 2 project in Visual Studio 2010, and we'll incrementally add features to create a complete functioning application. Along the way, we'll cover database access, list and details views, data update pages, data validation, using master pages for consistent page layout, AJAX for page updates and validation, user membership, and more.

You can follow along step by step, or you can download the completed application from http://mvcmusicstore.codeplex.com.

You can use either Visual Studio 2010 or the free Visual Web Developer 2010 Express to build the application. You can use either SQL Server or the free SQL Server Express to host the database. The Express tools can be installed using the Web Platform Installer here: http://www.microsoft.com/web/platform/tools.aspx

File / New Project

We'll start by selecting the New Project from the File menu in Visual Studio. This brings up the New Project dialog.

We'll select the Visual C# / Web Templates group on the left, then choose the "ASP.NET MVC 2 Empty Web Application" template in the center column. Name your project MvcMusicStore and press the OK button.

This will create our project. Let's take a look at the folders that are included in our application in the Solution Explorer on the right side.

The Empty MVC 2 Solution isn't completely empty - it adds a basic folder structure:

ASP.NET MVC makes use of some basic conventions for folder names:

Folder

Purpose

/Controllers

Controllers respond to input from the browser, decide what to do with it, and return response to the user.

/Views

Views hold our UI templates

/Models

Models hold and manipulate data

/Content

This folder holds our images, CSS, and any other static content

/Scripts

This folder holds our JavaScript files

/App_Data

This folder holds data files which can be read and updated by the application

These folders are included even in an Empty ASP.NET MVC application because the framework makes some assumptions based on folder in naming conventions. For instance, controllers look for views in the Views folder by default, so sticking with the basic conventions not only makes it easier for other developers to understand your project, it simplifies your code.

ASP.NET MVC makes extensive use of conventions to simplify the development process; we'll point them out as we go.

Controllers

Controllers run the show in an MVC application, so we'll begin there. We'll want to get our site started with a Home page, so we'll add a Controller to handle the Home page of the site. We'll follow the convention and call it HomeController.

Adding a HomeController

Right-click the controllers folder and select "Add", then "Controller..."

Change the Controller Name to HomeController and press the Add button.

This will create a new file, HomeController.cs, with the following code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
  
namespace MvcMusicStore.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/
  
        public ActionResult Index()
        {
            return View();
        }
  
    }
}

To start as simply as possible, let's replace that with a simple method that just returns a string. Let's make two simple changes:

  • Change the method to return a string instead of an ActionResult
  • Change the return statement to return "Hello from Home"

The method should now look like this:

public string Index()
{
    return "Hello from Home";
}

Running the Application

Now we can run the site. We can do using any of the following:

  • Choose the Debug | Start Debugging menu item
  • Click the Green arrow button in the toolbar
  • Use the keyboard shortcut, F5.

Okay, that was pretty quick - we created a new website, added a three line function, and we've got text in a browser. Not rocket science, but we've got a start.

Note: Visual Studio includes the ASP.NET Development Server, which will run your website on a random free "port" number. In the screenshot above, the site is running at http://localhost:26641/, so it's using port 26641. Your port number will be different. When we talk about URL's like /Store/Browse in this tutorial, that will go after the port number. Assuming a port number of 26641, browsing to /Store/Browse will mean browsing to http://localhost:26641/Store/Browse.

Now let's set up a controller for our Store. The store has three levels:

  • The Store Index lists the genres our store carries
  • The Browse page lists all albums in a genre
  • The Details page shows information for a specific album

We'll start by adding a new StoreController, just like we created the HomeController. If you haven't already, stop running the application either by closing the browser or selecting the Debug | Stop Debugging menu item.

Now add a new StoreController:

The new controller will already have an Index method. We'll also need to add methods to handle the two other pages in the store: Browse, and Details. These methods are called Controller Actions, and as you've already seen with the HomeController Index() Controller Action, their job is to respond to URL requests and (generally speaking) put content on a page.

We'll start by changing the StoreController.Index method to return the string "Hello from Store.Index()" and we'll add similar methods for Browse and Details:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
  
namespace MvcMusicStore.Controllers
{
    public class StoreController : Controller
    {
        //
        // GET: /Store/
  
        public string Index()
        {
            return "Hello from Store.Index()";
        }
  
        //
        // GET: /Store/Browse
  
        public string Browse()
        {
            return "Hello from Store.Browse()";
        }
  
        //
        // GET: /Store/Details
  
        public string Details()
        {
            return "Hello from Store.Details()";
        }
    }
}

Run the project again and browse to /Store/Details:

That's great, but these are just simple strings. Let's make them dynamic, so they take information from the URL and display it in the page output. First we'll change the Details action to read and display an input parameter named ID.

//
// GET: /Store/Details/5
public string Details(int id)
{
    string message = "Store.Details, ID = " + id;
    return Server.HtmlEncode(message);
}

Run the application and browse to /Store/Details/5. The controller action read the ID from the URL and filled it into the string that we wrote out to the browser:

That was especially easy because ID is a special case. ASP.NET MVC uses a system called routing to map URL values to controller action parameters, and it includes a default "route" with an ID parameter already set up in all new projects. That's configurable, and we'll look at that more later.

We can also read querystring values from a URL without any routing changes. Alter the Browse Controller action to accept and Genre string parameter:

//
// GET: /Store/Browse/
public string Browse()
{
    string message = "Store.Browse, Genre = " +
    Server.HtmlEncode(Request.QueryString["genre"]);
    return Server.HtmlEncode(message);
}

Now let's browse to /Store/Browse?Genre=Disco

Note: We're using the Server.HtmlEncode utility method to sanitize the user input. This prevents users from injecting Javascript into our View with a link like /Store/Browse?Genre=<script>window.location='http://hackersite.com'</script>.

Let's recap what we've done so far:

  • We've created a new project in Visual Studio
  • We've overviewed the basic folder structure of an ASP.NET MVC application
  • We've learned how to run our website using the ASP.NET Development Server
  • We've created two Controllers with four Controller Actions which respond to URL requests and return text to the browser


You've finished learning Part 1 - Overview, File/New Project, and Controllers. Next: Part 2 - Views and View Models

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章