Professional ASP.NET MVC 3

( 1 )

Overview

New edition of the top book on MVC from the top ASP.NET experts at Microsoft!

MVC 3.0 is the latest update to Microsoft's Model-View-Controller technology, which enables developers to build dynamic, data-driven web sites. This in-depth book shows you step by step how to use MVC 3.0. Written by top ASP.NET MVC experts at Microsoft, the latest edition of this popular book covers new and updated features such as the new View engine, Razor, NuGet, and much more. The book's practical...

See more details below
Other sellers (Paperback)
  • All (30) from $2.26   
  • New (15) from $5.99   
  • Used (15) from $2.26   
Professional ASP.NET MVC 3

Available on NOOK devices and apps  
  • NOOK Devices
  • Samsung Galaxy Tab 4 NOOK
  • NOOK HD/HD+ Tablet
  • NOOK
  • NOOK Color
  • NOOK Tablet
  • Tablet/Phone
  • NOOK for Windows 8 Tablet
  • NOOK for iOS
  • NOOK for Android
  • NOOK Kids for iPad
  • PC/Mac
  • NOOK for Windows 8
  • NOOK for PC
  • NOOK for Mac
  • NOOK for Web

Want a NOOK? Explore Now

NOOK Book (eBook)
$25.99
BN.com price
(Save 42%)$44.99 List Price

Overview

New edition of the top book on MVC from the top ASP.NET experts at Microsoft!

MVC 3.0 is the latest update to Microsoft's Model-View-Controller technology, which enables developers to build dynamic, data-driven web sites. This in-depth book shows you step by step how to use MVC 3.0. Written by top ASP.NET MVC experts at Microsoft, the latest edition of this popular book covers new and updated features such as the new View engine, Razor, NuGet, and much more. The book's practical tutorials reinforce concepts and allow you create real-world applications. Topics include controllers and actions, forms and HTML helpers, Ajax, unit testing, and much more.

  • Shows developers and programmers how to use ASP.NET MVC 3.0, Microsoft's new version of its Model-View-Controller technology for developing dynamic, data-driven web sites
  • Features an expert author team-all are members of Microsoft's ASP.NET team
  • Uses a step-by-step approach to explain all major features and functionalities and provides practical tutorials to allow you to create real-world applications
  • Goes into theory as well as practical application and covers such topics as Razor, NuGet (PowerShell inside Visual Studio 2010), and new layout features

Move your development skills to the next level with MVC 3.0 and Professional ASP.NET MVC 3.0.

Read More Show Less

Product Details

  • ISBN-13: 9781118076583
  • Publisher: Wiley
  • Publication date: 8/9/2011
  • Edition number: 1
  • Pages: 432
  • Sales rank: 933,481
  • Product dimensions: 7.40 (w) x 9.20 (h) x 1.00 (d)

Meet the Author

Jon Galloway works at Microsoft as part of the Server and Tools online group, where he focuses on the ASP.NET community and the ASP.NET website.

Phil Haack is a senior program manager at Microsoft on the Web Platform and Tools team. His areas of responsibility include ASP.NET MVC and NuGet.

Brad Wilson has nearly 20 years of experience in professional software development and web development. He currently works on the ASP.NET MVC project at Microsoft.

K. Scott Allen is the founder of OdeToCode LLC where he provides custom development, consulting, and mentoring services for clients around the world.

Read More Show Less

Read an Excerpt

Professional ASP.NET MVC 3


By Jon Galloway Phil Haack Brad Wilson K. Scott Allen

John Wiley & Sons

Copyright © 2011 John Wiley & Sons, Ltd
All right reserved.

ISBN: 978-1-1180-7658-3


Chapter One

Getting Started

— By Jon Galloway

WHAT'S IN THIS CHAPTER?

* Understanding ASP.NET MVC

* An ASP.NET MVC 3 overview

* How to create MVC 3 applications

* How MVC applications are structured

This chapter gives you a quick introduction to ASP.NET MVC, explains how ASP.NET MVC 3 fits into the ASP.NET MVC release history, summarizes what's new in ASP.NET MVC 3, and shows you how to set up your development environment to build ASP.NET MVC 3 applications.

This is a Professional Series book about a version 3 web framework, so we're going to keep the introductions short. We're not going to spend any time convincing you that you should learn ASP.NET MVC. We're assuming that you've bought this book for that reason, and that the best proof of software frameworks and patterns is in showing how they're used in real-world scenarios.

A QUICK INTRODUCTION TO ASP.NET MVC

ASP.NET MVC is a framework for building web applications that applies the general Model View Controller pattern to the ASP.NET framework. Let's break that down by first looking at how ASP.NET MVC and the ASP.NET framework are related.

How ASP.NET MVC Fits in with ASP.NET

When ASP.NET 1.0 was first released in 2002, it was easy to think of ASP.NET and Web Forms as one and the same thing. ASP.NET has always supported two layers of abstraction, though:

* System.Web.UI: The Web Forms layer, comprising server controls, ViewState, and so on

* System.Web: The plumbing, which supplies the basic web stack, including modules, handlers, the HTTP stack, and so on

The mainstream method of developing with ASP.NET included the whole Web Forms stack — taking advantage of drag-and-drop controls, semi-magical statefulness, and wonderful server controls while dealing with the complications behind the scenes (an often confusing page life cycle, less than optimal HTML, and so on).

However, there was always the possibility of getting below all that — responding directly to HTTP requests, building out web frameworks just the way you wanted them to work, crafting beautiful HTML — using Handlers, Modules, and other handwritten code. You could do it, but it was painful; there just wasn't a built-in pattern that supported any of those things. It wasn't for lack of patterns in the broader computer science world, though. By the time ASP.NET MVC was announced in 2007, the MVC pattern was becoming one of the most popular ways of building web frameworks.

The MVC Pattern

Model-View-Controller (MVC) has been an important architectural pattern in computer science for many years. Originally named Thing-Model-View-Editor in 1979, it was later simplified to Model-View-Controller. It is a powerful and elegant means of separating concerns within an application (for example, separating data access logic from display logic) and applies itself extremely well to web applications. Its explicit separation of concerns does add a small amount of extra complexity to an application's design, but the extraordinary benefits outweigh the extra effort. It has been used in dozens of frameworks since its introduction. You'll find MVC in Java and C++, on Mac and on Windows, and inside literally dozens of frameworks.

The MVC separates the user interface of an application into three main aspects:

* The Model: A set of classes that describes the data you're working with as well as the business rules for how the data can be changed and manipulated

* The View: Defines how the application's user interface (UI) will be displayed

* The Controller: A set of classes that handles communication from the user, overall application flow, and application-specific logic

MVC as Applied to Web Frameworks

The MVC pattern is used frequently in web programming. With ASP.NET MVC, it's translated roughly as:

* Models: These are the classes that represent the domain you are interested in. These domain objects often encapsulate data stored in a database as well as code used to manipulate the data and enforce domain-specific business logic. With ASP.NET MVC, this is most likely a Data Access Layer of some kind using a tool like Entity Framework or NHibernate combined with custom code containing domain-specific logic.

* View: This is a template to dynamically generate HTML . We cover more on that in Chapter 3 when we dig into views.

* Controller: This is a special class that manages the relationship between the View and Model. It responds to user input, talks to the Model, and it decides which view to render (if any). In ASP.NET MVC, this class is conventionally denoted by the suffix Controller.

The Road to MVC 3

Two short years have seen three major releases of ASP.NET MVC and several more interim releases. In order to understand ASP.NET MVC 3, it's important to understand how we got here. This section describes the contents and background of each of the three major ASP.NET MVC releases.

ASP.NET MVC 1 Overview

In February 2007, Scott Guthrie ("ScottGu") of Microsoft sketched out the core of ASP.NET MVC while flying on a plane to a conference on the East Coast of the United States. It was a simple application, containing a few hundred lines of code, but the promise and potential it offered for parts of the Microsoft web developer audience was huge.

As the legend goes, at the Austin ALT.NET conference in October 2007 in Redmond, Washington, ScottGu showed a group of developers "this cool thing I wrote on a plane" and asked if they saw the need and what they thought of it. It was a hit. In fact, many people were involved with the original prototype, codenamed Scalene. Eilon Lipton e-mailed the first prototype to the team in September 2007, and he and ScottGu bounced prototypes, code, and ideas back and forth.

Even before the official release, it was clear that ASP.NET MVC wasn't your standard Microsoft product. The development cycle was highly interactive: there were nine preview releases before the official release, unit tests were made available, and the code shipped under an open source license. All of these highlighted a philosophy that placed a high value in community interaction throughout the development process. The end result was that the official MVC 1.0 release — including code and unit tests — had already been used and reviewed by the developers who would be using it. ASP.NET MVC 1.0 was released on 13 March 2009.

ASP.NET MVC 2 Overview

ASP.NET MVC 2 was released just one year later, in March 2010. Some of the main features in MVC 2 included:

* UI helpers with automatic scaffolding with customizable templates

* Attribute-based Model validation on both client and server

* Strongly-typed HTML helpers

* Improved Visual Studio tooling

There were also lots of API enhancements and "pro" features, based on feedback from developers building a variety of applications on ASP.NET MVC 1, such as:

* Support for partitioning large applications into areas

* Asynchronous Controllers support

* Support for rendering subsections of a page/site using Html.RenderAction

* Lots of new helper functions, utilities, and API enhancements

One important precedent set by the MVC 2 release was that there were very few breaking changes. I think this is a testament to the architectural design of ASP.NET MVC, which allows for a lot of extensibility without requiring core changes.

ASP.NET MVC 3 Overview

ASP.NET MVC 3 (generally abbreviated as MVC 3 from now on) shipped just 10 months after MVC 2, driven by the release date for Web Matrix. If MVC 3 came in a box, it might say something like this on the front:

* Expressive Views including the new Razor View Engine!

* .NET 4 Data Annotation Support!

* Streamlined validation with improved Model validation!

* Powerful hooks with Dependency Resolution and Global Action Filters!

* Rich JavaScript support with unobtrusive JavaScript, jQuery Validation, and JSON binding!

* Now with NuGet!!!!

For those who have used previous versions of MVC, we'll start with a quick look at some of these major features.

Razor View Engine

Razor is the first major update to rendering HTML since ASP.NET 1.0 shipped almost a decade ago. The default view engine used in MVC 1 and 2 was commonly called the Web Forms View Engine, because it uses the same ASPX/ASCX/MASTER files and syntax used in Web Forms. It works, but it was designed to support editing controls in a graphical editor, and that legacy shows. An example of this syntax in a Web Forms page is shown here:

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<MvcMusicStore.ViewModels.Store BrowseViewModel>" %><p> <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server"> Browse Albums </asp:Content> <p> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <p> <div class="genre"> <H4><em> <%: Model.Genre.Name %></em> Albums</H4> <ul id="album-list"> <% foreach (var album in Model.Albums) { %><p> <li> <a href=" <%: Url.Action("Details", new { id = album.AlbumId }) %>"> <img alt=" <%: album.Title %>" src="<br>
<%: album.AlbumArtUrl %>" /> <span> <%: album.Title %></span> </a> </li> <p> <% } %></ul> <p> <p> </asp:Content7gt;

Razor was designed specifically as a view engine syntax. It has one main focus: code-focused templating for HTML generation. Here's how that same markup would be generated using Razor:

@model MvcMusicStore.Models.Genre

@{ViewBag.Title = "Browse Albums";}

<div class="genre">

@Model.Name Albums

<ul id="album-list"> @foreach (var album in Model.Albums) { <li> <a href="@Url.Action("Details", new { id = album.AlbumId })"> <img alt="@album.Title" src="@album.AlbumArtUrl" /> <span>@album.Title</span> </a> </li> } </ul>

The Razor syntax is easier to type, and easier to read. Razor doesn't have the XML-like heavy syntax of the Web Forms view engine.

We've talked about how working with the Razor syntax feels different. To put this in more quantifiable terms, let's look at the team's design goals in creating the Razor syntax:

* Compact, expressive, and fluid: Razor's (ahem) sharp focus on templating for HTML generation yields a very minimalist syntax. This isn't just about minimizing keystrokes — although that's an obvious result — it's about how easy it is to express your intent. A key example is the simplicity in transitions between markup and code. You can see this in action when writing out some model properties in a loop:

@foreach (var album in Model.Albums) { <li>

<a href="@Url.Action("Details", new { id = album.AlbumId })"> <img alt="@album.Title" src="@album.AlbumArtUrl" /> <span>@album.Title</span> </a> </li> }

Razor also simplifies markup with an improvement on the Master Pages concept — called Layouts — that is both more flexible and requires less code.

* Not a new language: Razor is a syntax that lets you use your existing .NET coding skills in a template in a very intuitive way. Scott Hanselman summarized this pretty well when describing his experiences learning Razor:

I kept [...] going cross-eyed when I was trying to figure out what the syntax rules were for Razor until someone said stop thinking about it, just type an "at" sign and start writing code and I realize that there really is no Razor.

— Hanselminutes #249: On WebMatrix with Rob Conery http://hanselminutes.com/default.aspx?showID=268

* Easy to learn: Precisely because Razor is not a new language, it's easy to learn. You know HTML, you know .NET; just type HTML and hit the @ sign whenever you need to write some .NET code.

* Works with any text editor: Because Razor is so lightweight and HTML-focused, you're free to use the editor of your choice. Visual Studio's syntax highlighting and IntelliSense features are nice, but it's simple enough that you can edit it in any text editor.

* Great IntelliSense: Though Razor was designed so that you shouldn't need IntelliSense to work with it, IntelliSense can come in handy for things like viewing the properties your model object supports. For those cases, Razor does offer nice IntelliSense within Visual Studio, as shown in Figure 1-1.

* Unit testable: The Razor view engine's core compilation engine has no dependencies on System.Web or ASP.NET whatsoever — it can be executed from unit tests, or even from the command line. Though there isn't direct tooling support for this yet, it's possible to use systems like David Ebbo's Visual Studio Single File Generator (http://visualstudiogallery.msdn.microsoft.com/1f6ec6ff-e89b-4c47-8e79-d2d68df894ec/) to compile your views into classes that you can then load and test like any other object.

This is just a quick highlight of some of the reasons that Razor makes writing View code really easy and, dare I say, fun. We'll talk about Razor in a lot more depth in Chapter 3.

Validation Improvements

Validation is an important part of building web applications, but it's never fun. I've always wanted to spend as little time as possible writing validation code, as long as I was confident that it worked correctly.

MVC 2's attribute-driven validation system removed a lot of the pain from this process by replacing repetitive imperative code with declarative code. However, support was focused on a short list of top validation scenarios. There were plenty of cases where you'd get outside of the "happy path" and have to write a fair amount more code. MVC 3 extends the validation support to cover most scenarios you're likely to encounter. For more information on validation in ASP.NET MVC, see chapter 6.

.NET 4 Data Annotation Support

MVC 2 was compiled against .NET 3.5 and thus didn't support any of the .NET 4 Data Annotations enhancements. MVC 3 picks up some new, very useful validation features available due to .NET 4 support. Some examples include:

* MVC 2's DisplayName attribute wasn't localizable, whereas the .NET 4 standard System .ComponentModel.DataAnnotations Display attribute is.

* ValidationAttribute was enhanced in .NET 4 to better work with the validation context for the entire model, greatly simplifying cases like validators that compare or otherwise reference two model properties.

Streamlined Validation with Improved Model Validation

MVC 3's support for the .NET 4 IValidatableObject interface deserves individual recognition. You can extend your model validation in just about any conceivable way by implementing this interface on your model class and implementing the Validate method, as shown in the following code:

public class VerifiedMessage : IValidatableObject { public string Message { get; set; } public string AgentKey { get; set; } public string Hash { get; set; }

public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { if (SecurityService.ComputeHash(Message, AgentKey) != Hash) yield return new ValidationResult("Agent compromised"); } }

Rich JavaScript Support

JavaScript is an important part of any modern web application. ASP.NET MVC 3 adds some significant support for client-side development, following current standards for top quality JavaScript integration. For more information on the new JavaScript related features in ASP.NET MVC 3, see Chapter 8.

Unobtrusive JavaScript

Unobtrusive JavaScript is a general term that conveys a general philosophy, similar to the term REST (for Representational State Transfer). The high-level description is that unobtrusive JavaScript doesn't affect your page markup. For example, rather than hooking in via event attributes like onclick and onsubmit, the unobtrusive JavaScript attaches to elements by their ID or class.

Unobtrusive JavaScript makes a lot of sense when you consider that your HTML document is just that — a document. It's got semantic meaning, and all of it — the tag structure, element attributes, and so on — should have a precise meaning. Strewing JavaScript gunk across the page to facilitate interaction (I'm looking at you, __doPostBack!) harms the content of the document.

MVC 3 supports unobtrusive JavaScript in two ways:

* Ajax helpers (such as Ajax.ActionLink and Ajax.BeginForm) render clean markup for the FORM tag, wiring up behavior leveraging extensible attributes (data- attributes) and jQuery.

(Continues...)



Excerpted from Professional ASP.NET MVC 3 by Jon Galloway Phil Haack Brad Wilson K. Scott Allen Copyright © 2011 by John Wiley & Sons, Ltd. Excerpted by permission of John Wiley & Sons. All rights reserved. No part of this excerpt may be reproduced or reprinted without permission in writing from the publisher.
Excerpts are provided by Dial-A-Book Inc. solely for the personal use of visitors to this web site.

Read More Show Less

Table of Contents

FOREWORD xxiii

INTRODUCTION xxv

CHAPTER 1: GETTING STARTED 1

CHAPTER 2: CONTROLLERS 23

CHAPTER 3: VIEWS 39

CHAPTER 4: MODELS 69

CHAPTER 5: FORMS AND HTML HELPERS 93

CHAPTER 6: DATA ANNOTATIONS AND VALIDATION 117

CHAPTER 7: SECURING YOUR APPLICATION 135

CHAPTER 8: AJAX 179

CHAPTER 9: ROUTING 211

CHAPTER 10: NUGET 239

CHAPTER 11: DEPENDENCY INJECTION 271

CHAPTER 12: UNIT TESTING 291

CHAPTER 13: EXTENDING MVC 315

CHAPTER 14: ADVANCED TOPICS 339

INDEX 389

Read More Show Less

Customer Reviews

Average Rating 1
( 1 )
Rating Distribution

5 Star

(0)

4 Star

(0)

3 Star

(0)

2 Star

(0)

1 Star

(1)

Your Rating:

Your Name: Create a Pen Name or

Barnes & Noble.com Review Rules

Our reader reviews allow you to share your comments on titles you liked, or didn't, with others. By submitting an online review, you are representing to Barnes & Noble.com that all information contained in your review is original and accurate in all respects, and that the submission of such content by you and the posting of such content by Barnes & Noble.com does not and will not violate the rights of any third party. Please follow the rules below to help ensure that your review can be posted.

Reviews by Our Customers Under the Age of 13

We highly value and respect everyone's opinion concerning the titles we offer. However, we cannot allow persons under the age of 13 to have accounts at BN.com or to post customer reviews. Please see our Terms of Use for more details.

What to exclude from your review:

Please do not write about reviews, commentary, or information posted on the product page. If you see any errors in the information on the product page, please send us an email.

Reviews should not contain any of the following:

  • - HTML tags, profanity, obscenities, vulgarities, or comments that defame anyone
  • - Time-sensitive information such as tour dates, signings, lectures, etc.
  • - Single-word reviews. Other people will read your review to discover why you liked or didn't like the title. Be descriptive.
  • - Comments focusing on the author or that may ruin the ending for others
  • - Phone numbers, addresses, URLs
  • - Pricing and availability information or alternative ordering information
  • - Advertisements or commercial solicitation

Reminder:

  • - By submitting a review, you grant to Barnes & Noble.com and its sublicensees the royalty-free, perpetual, irrevocable right and license to use the review in accordance with the Barnes & Noble.com Terms of Use.
  • - Barnes & Noble.com reserves the right not to post any review -- particularly those that do not follow the terms and conditions of these Rules. Barnes & Noble.com also reserves the right to remove any review at any time without notice.
  • - See Terms of Use for other conditions and disclaimers.
Search for Products You'd Like to Recommend

Recommend other products that relate to your review. Just search for them below and share!

Create a Pen Name

Your Pen Name is your unique identity on BN.com. It will appear on the reviews you write and other website activities. Your Pen Name cannot be edited, changed or deleted once submitted.

 
Your Pen Name can be any combination of alphanumeric characters (plus - and _), and must be at least two characters long.

Continue Anonymously
Sort by: Showing all of 2 Customer Reviews
  • Anonymous

    Posted August 11, 2012

    Great book

    Good book. Examples arent that great. But provides clear concept. Great work.

    1 out of 1 people found this review helpful.

    Was this review helpful? Yes  No   Report this review
  • Anonymous

    Posted September 27, 2011

    No text was provided for this review.

Sort by: Showing all of 2 Customer Reviews

If you find inappropriate content, please report it to Barnes & Noble
Why is this product inappropriate?
Comments (optional)