Asp.Net MVC Intro

50
A new “pluggable” web framework * Asp.Net MVC Stefano Paluello [email protected] http://stefanopaluello.wordpress.com Twitter: @palutz

description

An introduction to Asp.Net MVC @ Torino Technologies Group (http://www.torinotechnologiesgroup.it)

Transcript of Asp.Net MVC Intro

Page 1: Asp.Net MVC Intro

A new “pluggable” web framework

*Asp.Net MVC

Stefano [email protected]://stefanopaluello.wordpress.com Twitter: @palutz

Page 2: Asp.Net MVC Intro

*Agenda

*MVC and Asp.Net

*The Model, the View and the Controller (looks like “The Good, the Bad and the Ugly” )

*HtmlHelper and PartialView

*Routing

*Filters

*TDD with Asp.Net MVC

Page 3: Asp.Net MVC Intro

*MVC and Asp.Net

From WebForm to MVC

Page 4: Asp.Net MVC Intro

*Asp.Net

*Asp.Net was introduced in 2002 (.Net 1.0)

*It was a big improvement from the “spaghetti code” that came with Asp classic

*It introduced a new programming model, based on Events, Server-side Controls and “stateful” Form (Session, Cache, ViewState): the RAD/VB-like development model for the web.

*It allowed a lot of developers to deal with the Web, also if they have limited or no skills at all in HTML and JavaScript.

Build with productivity in mind

Page 5: Asp.Net MVC Intro

*Windows Form and Web Form models

Code

Action

Reaction

Server

Server

Serialize/DeserializeWebform state

CodeHttpRequest

HttpResponse

Page 6: Asp.Net MVC Intro

*That’s cool… But

*Events and State management are not HTTP concepts (you need a quite big structure to manage them)

*The page life cycle, with all the events handler, can become really complicated and also delicate (easy to break)

*You have low control over the HTML code generated

*The complex Unique ID values for the server-side controls don’t fit well with Javascript functions

*There is a fake feeling of separation of concerns with the Asp.Net’s code behind

*Automated test could be challenging.

Page 7: Asp.Net MVC Intro

*The Web development today is

*Web standards

*HTTP

*CSS

*Javascript

*REST (Representational State Transfer), represents an application in terms of resources, instead of SOAP, the Asp.Net web service base technology

*Agile and TDD

Page 8: Asp.Net MVC Intro

*So… Welcome, Asp.Net MVC

Page 9: Asp.Net MVC Intro

*Asp.Net MVC “tenets”

*Be extensible, maintainable and flexible

*Be testable

*Have a tight control over HTML and HTTP

*Use convention over configuration

*DRY: don’t repeat yourself

*Separation of concerns

Page 10: Asp.Net MVC Intro

*The MVC pattern

Page 11: Asp.Net MVC Intro

*Separation of concerns

*Separation of concerns comes naturally with MVC

*Controller knows how to handle a request, that a View exist, and how to use the Model (no more)

*Model doesn’t know anything about a View

*View doesn’t know there is a Controller

Page 12: Asp.Net MVC Intro

*Asp.Net > Asp.Net MVC

*Based on the .Net platform (quite straightforward )

*Master page

*Forms authentication

*Membership and Role providers

*Profiles

*Internationalization

*Cache

Asp.Net MVC is built on (the best part of) Asp.Net

Page 13: Asp.Net MVC Intro

*Asp.Net and Asp.Net MVC run-time stack

Page 14: Asp.Net MVC Intro

*DemoFirst Asp.Net MVC application

Page 15: Asp.Net MVC Intro

*Asp.Net MVCThe structure of the project

Page 16: Asp.Net MVC Intro

*Convention over configuration

*Asp.Net MVC projects have some top-level (and core) directories that you don’t need to setup in the config:

*Controllers, where you put the classes that handle the request

*Models, where you put the classes that deal with data

*Views, where you put the UI template files

*Scripts, where you put Javascript library files and scripts (.js)

*Content, where you put CSS and image files, and so on

*App_Data, where you put data files

Page 17: Asp.Net MVC Intro

*Models, Controllers and Views

Page 18: Asp.Net MVC Intro

*The Models

*Classes that represent your application data

*Contain all the business, validation, and data acccess logic required by your application

*Three different kind of Model:

*data being posted on the Controller

*data being worked on in the View

*domain-specific entities from you business tier

*You can create your own Data Model leveraging the most recommend data access technologies

The representation of our data

Page 19: Asp.Net MVC Intro

*An actual Data Model using Entity Framework

4.0

Page 20: Asp.Net MVC Intro

*ViewModel Pattern

*Additional layer to abstract the data for the Views from our business tier

*Can leverage the strongly typed View template features

*The Controller has to know how to translate from the business tier Entity to the ViewModel one

*Enable type safety, compile-time checking and Intellisense

*Useful specially in same complex scenarios

Create a class tailored on our specific View scenarios

Page 21: Asp.Net MVC Intro

*Model vs.ViewModel

public ActionResult Customer(int id)

{

ViewData[“Customer”] = MyRepository.GetCustomerById(id);

ViewData[“Orders”] = MyRepository.GetOrderforCustomer(id);

return View();

}

public class CustomerOrderMV

{

Customer CustomerData { get; set;}

Order CustomerOrders { get; set;}

}

public ActionResult Customer(int id)

{

CustomerOrderMV custOrd = MyRepository.GetCustomerOrdersById(id);

ViewData.Model = custOrd;

return View();

}

Page 22: Asp.Net MVC Intro

*Validation

*Validation and business rule logic are the keys for any application that work with data

*Schema validation comes quite free if you use OR/Ms

*Validation and Business Rule logic can be quite easy too using the Asp.Net MVC 2 Data Annotations validation attributes (actually these attributes were introduced as a part of the Asp.Net Dynamic Data)

Adding Validation Logic to the Models

Page 23: Asp.Net MVC Intro

*Data Annotations validation

[MetadataType(typeof(Blog_Validation))]

public partial class Blog

{

}

[Bind(Exclude = "IdBlog")]

public class Blog_Validation

{

[Required(ErrorMessage= "Title required")]

[StringLength(50, ErrorMessage = "…")]

[DisplayName("Blog Title")]

public String Title { get; set; }

[Required(ErrorMessage = "Blogger required")]

[StringLength(50, ErrorMessage = “…")]

public String Blogger { get; set; }ù

}

How to add validation to the Model through Metadata

Page 24: Asp.Net MVC Intro

*DemoAsp.Net MVC Models

Page 25: Asp.Net MVC Intro

*The Controllers

*The controllers are responsible for responding to the user request

*Have to implement at least the IController interface, but better if you use the ControllerBase or the Controller abstract classes (with more API and resources, like the ControllerContext and the ViewData, to build your own Controller)

Page 26: Asp.Net MVC Intro

*My own Controller

* using System;

* using System.Web.Routing;

* namespace System.Web.Mvc

* {

* // Summary: Defines the methods that are required for a controller.

* public interface IController

* {

* // Summary: Executes the specified request context.

* // Parameters:

* // requestContext: The request context.

* void Execute(RequestContext requestContext);

* }

* } * using System.Web;

* using System.Web.Mvc;

* public class SteoController : IController

* {

* public void Execute(System.Web.Routing.RequestContext requestContext)

* {

* HttpResponseBase response = requestContext.HttpContext.Response;

* response.Write("<h1>Hello MVC World!</h1>");

* }

* }

Page 27: Asp.Net MVC Intro

*This reminds me something…

public interface IController

{void Execute(RequestContext requestContext);

}

public interface IHttpHandler

{void ProcessRequest(HttpContext context);

bool IsReusable { get; }

}

*They look quite similar, aren’t they?

*The two methods respond to a request and write back the output to a response

*The Page class, the default base class for ASPX pages in Asp.Net, implements the IHttpHandler.

Page 28: Asp.Net MVC Intro

*The Action Methods

*All the public methods of a Controller class become Action methods, which are callable through an HTTP request

*Actually, only the public methods according to the defined Routes can be called

Page 29: Asp.Net MVC Intro

*The ActionResult

*Actions, as Controller’s methods, have to respond to user input, but they don’t have to manage how to display the output

*The pattern for the Actions is to do their own work and then return an object that derives from the abstract base class ActionResult

*ActionResult adhere to the “Command pattern”, in which commands are methods that you want the framework to perform in your behalf

Page 30: Asp.Net MVC Intro

*The ActionResult

public abstract class ActionResult

{public abstract void ExecuteResult (ControllerContext context);

}

public ActionResult List()

{

ViewData.Model = // get data from a repository

return View();

}

Page 31: Asp.Net MVC Intro

*ActionResult types

*EmptyResult

*ContentResult

*JsonResult

*RedirectResult

*RedirectToRouteResult

*ViewResult

*PartialViewResult

*FileResult

*FilePathResult

*FileContentResult

*FileStreamResult

*JavaScriptResult

Asp.Net MVC has several types to help handle the response

Page 32: Asp.Net MVC Intro

*DemoAsp.Net MVC Controllers

Page 33: Asp.Net MVC Intro

*The Views

*The Views are responsible for providing the User Interface (UI) to the user

*The View receive a reference to a Model and it transforms the data in a format ready to be presented

Page 34: Asp.Net MVC Intro

*Asp.Net MVC’s View

*Handles the ViewDataDictionary and translate it into HTML code

* It’s an Asp.Net Page, deriving from ViewPage (System.Web.Mvc.ViewPage) which itself derives from Page (System.Web.UI.Page)

*By default it doesn’t include the “runat=server”, that you can add by yourself manually, if you want to use some server controls in your View (better to use only the “view-only” controls)

*Can take advantage of the Master Page, building Views on top of the Asp.Net Page infrastructure

Page 35: Asp.Net MVC Intro

* Asp.Net MVC Views’ syntax

*You will use <%: %> syntax (often referred to as “code nuggets”) to execute code within the View template.

* There are two main ways you will see this used:

*Code enclosed within <% %> will be executed

*Code enclosed within <%: %> will be executed, and the result will be output to the page

Page 36: Asp.Net MVC Intro

*DemoViews, Strongly Typed View, specify a View

Page 37: Asp.Net MVC Intro

*Html Helpers

*Html.Encode

*Html.TextBox

*Html.ActionLink, RouteLink

*Html.BeginForm

*Html.Hidden

*Html.DropDownList

*Html.ListBox

*Html.Password

*Html.RadioButton

*Html.Partial, RenderPartial

*Html.Action, RenderAction

*Html.TextArea

*Html.ValidationMessage

*Html.ValidationSummary

Methods shipped with Asp.Net MVC that help to deal with the HTML code.

MVC2 introduced also the strongly typed Helpers, that allow to use Model properties using a Lambda expression instead of a simple string

Page 38: Asp.Net MVC Intro

*Partial View

*Asp.Net MVC allow to define partial view templates that can be used to encapsulate view rendering logic once, and then reuse it across an application (help to DRY-up your code)

*The partial View has a .ascx extension and you can use like a HTML control

Page 39: Asp.Net MVC Intro

*Partial View Example

*The default Asp.Net MVC project just provide you a simple Partial View: the LogOnUserControl.ascx

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>

<%

if (Request.IsAuthenticated) {

%>

Welcome <b><%: Page.User.Identity.Name %></b>!

[ <%: Html.ActionLink("Log Off", "LogOff", "Account") %> ]

<%

}

else {

%>

[ <%: Html.ActionLink("Log On", "LogOn", "Account") %> ]

<%

}

%>

A simple example out of the box

Page 40: Asp.Net MVC Intro

*Ajax

*You can use the most popular libraries:

*Microsoft Asp.Net Ajax

* jQuery

*Can help to partial render a complex page (fit well with Partial View)

*Each Ajax routine will use a dedicated Action on a Controller

*With Asp.Net Ajax you can use the Ajax Helpers that come with Asp.Net MVC:

*Ajax.BeginForm

*AjaxOptions

* IsAjaxRequest

*…

It’s not really Asp.Net MVC but can really help you to boost your MVC application

Page 41: Asp.Net MVC Intro

*Routing

*Routing in Asp.Net MVC are used to:

*Match incoming requests and maps them to a Controller action

*Construct an outgoing URLs that correspond to Contrller action

How Asp.Net MVC manages the URL

Page 42: Asp.Net MVC Intro

*Routing vs URL Rewriting

*They are both useful approaches in creating separation between the URL and the code that handles the URL, in a SEO (Search Engine Optimization) way

*URL rewriting is a page centric view of URLs (eg: /products/redshoes.aspx rewritten as /products/display.aspx?productid=010)

*Routing is a resource-centric (not only a page) view of URLs. You can look at Routing as a bidirectional URL rewriting

Page 43: Asp.Net MVC Intro

*Defining Routes

public static void RegisterRoutes(RouteCollection routes)

{

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute(

"Default", // Route name

"{controller}/{action}/{id}", // URL with parameters

new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults );

}

protected void Application_Start()

{

AreaRegistration.RegisterAllAreas();

RegisterRoutes(RouteTable.Routes);

}

}

The default one…

Page 44: Asp.Net MVC Intro

*Route URL patterns

Page 45: Asp.Net MVC Intro

*StopRoutingHandler and IgnoreRoute

*You can use it when you don’t want to route some particular URLs.

*Useful when you want to integrate an Asp.Net MVC application with some Asp.Net pages.

Page 46: Asp.Net MVC Intro

*Filters

*Filters are declarative attribute based means of providing cross-cutting behavior

*Out of the box action filters provided by Asp.Net MVC:

*Authorize: to secure the Controller or a Controller Action

*HandleError: the action will handle the exceptions

*OutputCache: provide output caching to for the action methods

Page 47: Asp.Net MVC Intro

*DemoA simple Filter (Session Expire)

Page 48: Asp.Net MVC Intro

*TDD with Asp.Net MVCAsp.Net MVC was made with TDD in mind, but you can use also without it (if you want… )

*A framework designed with TDD in mind from the first step

*You can use your favorite Test Framework

*With MVC you can test the also your UI behavior (!)

Page 49: Asp.Net MVC Intro

*DemoTDD with Asp.Net MVC

Page 50: Asp.Net MVC Intro

*Let’s start the Open Session:

Asp.Net vs. Asp.Net MVC