DOC

ASP.NET MVC2 IN ACTION chapter1

By Laura Gonzalez,2014-06-27 03:48
14 views 0
ASP.NET MVC IN ACTION

Ch1_ Palermo _ ASP.NET_toProd

    1

    High-speed beginner ramp-up

    This chapter covers

    ? Introducing the MVC pattern

    ? Dissecting the default application template

    ? Creating your first ASP.NET MVC 2 project

    ? Handling user input

    ? Working with the view

    This chapter is intended to provide you with a quick, high-level overview of the ASP.NET MVC

    Framework. We’ll create a basic sample application, collect user input, and display some web

    pages.

    But first, let me introduce you to your new friend 1.1 Welcome to ASP.NET MVC

    ASP.NET MVC is a new web application framework from Microsoft. It was first unveiled in

    November 2007 and has since seen more than 10 releases and 2 major versions. With the

    high number of releases, this framework has received quite a bit of feedback and is much

    more stable than some other new frameworks from Microsoft, such as Windows Workflow

    Foundation. MVC stands for Model-View-Controller, a pattern thats becoming increasingly

    popular with web development frameworks.

    ASP.NET MVC is both an alternative and a complement to Web Forms, which means you

    won’t be dealing with pages and controls, postbacks or view state, or complicated event lifecycles. Instead, you’ll be defining controllers, actions, and views. The underlying ASP.NET Ch1_ Palermo _ ASP.NET_toProd platform is the same, however, so things like HTTP handlers and HTTP modules still apply, and you can mix MVC and Web Forms pages in the same application.

    We’ll cover all the major features of the framework throughout this book. Here are some

    of the benefits you’ll learn about:

Ch1_ Palermo _ ASP.NET_toProd

    ? Full control over HTML

    ? Full control over URLs

    ? Better separation of concerns

    ? Extensibility

    ? Testability

    As you read the chapters in this book, these benefits will become increasingly apparent.

    For now, we’ll briefly look at the underlying pattern the framework is based on. Why MVC? 1.2 The MVC pattern Where did it come from? The Model-View-Controller (MVC) pattern is an adaptation of a pattern generated from the

    Smalltalk community in the 1970s by Trygve Reenskaug. It was popularized for use on the

    web with the advent of Ruby on Rails in 2003.

    The components of MVC are straightforward:

    ? The model—The “thing” that your software is built around. If you were building a blog,

    your models might be post and comment. In some contexts, this might refer to a

    view-specific model, which you’ll learn about in the next chapter.

    ? The view—A visual representation of a model, given some context. It’s usually the

    resulting HTML that the framework renders to the browser, such as the HTML

    representing the blog post.

    ? The controllerA mediator. The controller processes input, acts upon the model, and

    decides what to dorender a view, redirect somewhere else, and so on. The controller

    might pull the most recent comments for a blog post and send them to a view.

    To see how these components interact with each other, take a look at figure 1.1.

Figure 1.1 The relationship between the model, view, and controller. The solid lines indicate a direct association, and the dashed lines indicate an indirect association. (Graphic and description used with

    Ch1_ Palermo _ ASP.NET_toProd

Ch1_ Palermo _ ASP.NET_toProd

    permission from Wikipedia.)

    Now that you have a rudimentary overview of the ASP.NET MVC Framework and the MVC

    pattern in general, you’re armed to create your first project. 1.3 Creating your first ASP.NET MVC 2 project

    We’ll create a web application with some guestbook features. Fire up Visual Studio, and go to

    File > New Project. You’re presented with the dialog box pictured in figure 1.2.

    NOTE

    The rest of this book assumes that you have ASP.NET MVC 2 installed, either on Visual

    Studio 2008 or on Visual Studio 2010. If you don’t, check the appendix for instructions on

    how to obtain it.

    Figure 1.2 The New Project dialog box. Notice the ASP.NET MVC 2 project templates.

    In the left pane, under Project Types, select Web. In the Templates pane, select ASP.NET

    MVC 2 Web Application. Give the application a name and location, and click OK. Ch1_ Palermo _ ASP.NET_toProd

Ch1_ Palermo _ ASP.NET_toProd

    You’re greeted with a dialog box (figure 1.3) that asks you if you want to create a unit

    test project. Normally we’d recommend creating a unit test project because most nontrivial projects need automated tests, but to keep this chapter focused, we’ll select No for now.

Figure 1.3 Visual Studio prompts you to create a unit test project. For now, select No.

    Your project is ready to go. Visual Studio created a number of folders for you. Let’s examine them and see what their purposes are:

    ? ContentStatic files such as CSS and images

    ? Controllers—Your application’s controller classes

    ? Models—Your application’s models

    ? ScriptsJavaScript files

    ? Views—Your application’s views

    Take a look at the folder structure for a minute. You’ll work with this structure for all your

    ASP.NET MVC projects, so everything will eventually look familiar.

    Ch1_ Palermo _ ASP.NET_toProd

Ch1_ Palermo _ ASP.NET_toProd

    The application that Visual Studio has given you is a working sample of the ASP.NET MVC

    Framework. That means you can just run it (Ctrl-F5) to see how it works. Go ahead and do

    that now.

    Your browser should be opened, and you should be looking at a page that looks like

    figure 1.4. Notice that the URL is simply http://localhost:port/. No path is specified. Let’s

    examine how this view was rendered.

Figure 1.4 The default ASP.NET MVC project template is fully functional.

    The initial request to the application was made to / (the root of the site). We can check

    the routes to see how the application responds to URLs. Routes are a way for you to

    customize the URLs that users use when interacting with your site. You’ll learn about routing

    in depth in chapter 16, but we’ll cover what you need to know to get started.

    Ch1_ Palermo _ ASP.NET_toProd

    Ch1_ Palermo _ ASP.NET_toProd

    public static void RegisterRoutes(RouteCollection routes) Routes are (by default) defined in the Global.asax. Open this file and you should see the { code shown in listing 1.1. routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Default", #1 "{controller}/{action}/{id}", #2 new { controller = "Home", action = "Index", id = UrlParameter.Optional } #3 ); }

    (Cueballs in Listing and Text)

    Notice that two entries are defined. The first is an IgnoreRoute, and that basically tells

    the framework not to worry about anything matching the specified path. In this case, it says

    not to process any paths containing the .axd file extension, such as Trace.axd. The second

    entry, MapRoute, is what defines how URLs are processed. This built-in route will suffice for

    a while, but later on you’ll want to add more routes in order to provide URLs that are specific to your application. Just like how previous versions of ASP.NET decided the URL for you

    based on the directory structure and the Web Form filename (such as Default.aspx),

    ASP.NET MVC projects come with a default URL structure. Applications that don’t require

    custom URL schemes will do just fine with the defaults.

    Each route has a name (#1), a URL definition (#2), and optional default values (#3). Our

    first request for / doesn’t have any of these URL pieces, so we look to the defaults. The

    default values are:

    ?

    controller"Home"

    ? action"Index"

    ? idOptional; defaults to null

    A note about routing

    The route with the template {controller}/{action}/{id} is a generic one and

    can be used for many different web requests. Tokens are denoted by the inclusion of

    curly braces, {}, and the word enclosed in braces matches a value the MVC Framework

    understands.

    The most common values that we’ll be interested in are controller and action. The

    controller route value is a special value that the System.Web.Mvc.MvcHandler

    class passes to the controller factory in order to instantiate a controller. This is also the Ch1_ Palermo _ ASP.NET_toProd

Ch1_ Palermo _ ASP.NET_toProd

    route we’ll be using for the rest of the chapter, so we’ll be content with a URL in the form

    of http://site.org/controllername/actionname.

    The basic route handler is an instance of IRouteHandler named MvcRouteHandler.

    We have complete control and could provide our own implementation of

    IRouteHandler if we wished, but we’ll save that for a later chapter. We know now that the controller is Home and the action is Index. Take a look in the

    Controllers folder and you’ll see a class called HomeController. By convention, all

    controller classes end with the word Controller. Open this class and you’ll see your first

    controller class (listing 1.2).

    [HandleError] public class HomeController : Controller #1 { public ActionResult Index() #2 { ViewData["Message"] = "Welcome to ASP.NET MVC!"; return View(); } public ActionResult About() { return View(); } }

    #1 Inherits from Controller #2 Declares action method

    Cueballs in text

    So what defines a controller in ASP.NET MVC anyway? For a class to be considered a

    controller, it must:

    ? End with the word Controller

    ? Inherit from System.Web.Mvc.Controller (or implement IController) (#1)

    ? Contain public methods that return ActionResult (these are called actions)

    (#2)

    We know that the Index action is going to be called. In this action method, we have

    these two statements: ViewData["Message"] = "Welcome to ASP.NET MVC!"; Ch1_ Palermo _ ASP.NET_toProd return View(); The first statement adds a string into a dictionary called ViewData. This is one way of

    passing data over to the view.

    View(). This is a helper method, Ch1_ Palermo _ ASP.NET_toProd defined in the Controller base class. It returns a new ViewResult object. ViewResult is one of the many ActionResult derivatives that you can return from actions.

    This ViewResult tells the framework to render a view. You have the option of providing

    a name for the view, but if you don’t—as in our caseit will just use the name of the action. The second line returns the result of a method called So where is this view located? We learned a few minutes ago that the default project

    structure contains a Views folder. By convention, views are located in a subfolder

    corresponding to the controller name. The name of the action (again by convention) is the

    same as the name of the view.

    Inside the Views folder you’ll find a folder for each controller in the application, along with

    a special one named Shared. Open the Home folder (because we’re dealing with

    HomeController), and open the Index.aspx file. It should look like listing 1.3.

    <%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %> <asp:Content ID="indexTitle" ContentPlaceHolderID="TitleContent" runat="server"> Home Page </asp:Content> <asp:Content ID="indexContent" ContentPlaceHolderID="MainContent" runat="server"> <h2><%= Html.Encode(ViewData["Message"]) %></h2> #A <p> To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC Website"> http://asp.net/mvc </a>. </p> </asp:Content>

    #A Uses view data from controller

    This view uses a master page, which is similar to what you’d see in an ASP.NET Web Forms project. If you’re curious, you can find this in /Views/Shared/Site.Master, but for now

    we can just focus on the view.

    This view will render the data provided by the controller. It shouldn’t contain any complex logic. Keeping the view simple makes it easy to read and maintain, especially because we’ll

    be mixing code with HTML. In listing 1.3, you can see that it outputs a message inside a

    code block denoted by <%= %> tags.

    To illustrate working with the ASP.NET MVC Framework, we’ll add some guestbook

    features to this application. The first step is adding a new controller.

    Ch1_ Palermo _ ASP.NET_toProd

1.4 Creating controllers and actions Ch1_ Palermo _ ASP.NET_toProd

    To add a new controller to our site, right-click on the Controllers folder and select Add

    Controller. In the Add Controller dialog box, shown in figure 1.5, type

    GuestBookController in the Controller Name text box. For now, don’t select the check

    box because we want to write our own actions. Click Add.

Figure 1.5 The Add Controller dialog box in Visual Studio

    A class will be created for you that looks like listing 1.4.

    public class GuestBookController : Controller { // // GET: /GuestBook/ public ActionResult Index() #1 { return View(); } }

    #1 Default action is automatically provided

    Cueballs in text

    Notice that an initial action method, Index, is created for you (#1). For this action, we

    don’t need to do anything except render a view. Let’s do that now. Ch1_ Palermo _ ASP.NET_toProd

    1.5 Creating views Ch1_ Palermo _ ASP.NET_toProd To create a view, right-click on the action method name and select Add View, as shown in figure 1.6.

Figure 1.6 Right-click on an action to create a view.

    You’ll see a dialog box asking you for some information about the view (shown in figure 1.7). The view name (by default) is the same name as the action, so verify that Index appears in the View name field. You can ignore the other options for now, and click Add.

    Ch1_ Palermo _ ASP.NET_toProd

Report this document

For any questions or suggestions please email
cust-service@docsford.com