Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Asp.Net MVC Intro


Published on

An introduction to Asp.Net MVC @ Torino Technologies Group (

Published in: Technology

Asp.Net MVC Intro

  1. 1. Asp.Net MVC<br />A new “pluggable” web framework<br />Stefano Paluello<br /><br /><br />Twitter: @palutz<br />
  2. 2. MVC and Asp.Net<br />The Model, the View and the Controller (looks like “The Good, the Bad and the Ugly” )<br />HtmlHelper and PartialView<br />Routing<br />Filters<br />TDD with Asp.Net MVC<br />Agenda<br />
  3. 3. MVC and Asp.Net<br />From WebForm to MVC<br />
  4. 4. Asp.Net<br />Asp.Net was introduced in 2002 (.Net 1.0)<br />It was a big improvement from the “spaghetti code” that came with Asp classic<br />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.<br />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.<br />Build with productivity in mind<br />
  5. 5. Windows Form and Web Form models<br />Server<br />Reaction<br />Code<br />Action<br />Server<br />HttpRequest<br />Serialize/<br />Deserialize<br />Webform state<br />Code<br />HttpResponse<br />
  6. 6. Events and State management are not HTTP concepts (you need a quite big structure to manage them)<br />The page life cycle, with all the events handler, can become really complicated and also delicate (easy to break)<br />You have low control over the HTML code generated<br />The complex Unique ID values for the server-side controls don’t fit well with Javascript functions<br />There is a fake feeling of separation of concerns with the Asp.Net’s code behind<br />Automated test could be challenging.<br />That’s cool… But<br />
  7. 7. Web standards<br />HTTP<br />CSS<br />Javascript<br />REST (Representational State Transfer), represents an application in terms of resources, instead of SOAP, the Asp.Net web service base technology<br />Agile and TDD<br />The Web development today is<br />
  8. 8. So… Welcome, Asp.Net MVC<br />WEB<br />
  9. 9. Asp.Net MVC “tenets”<br />Be extensible, maintainable and flexible<br />Be testable<br />Have a tight control over HTML and HTTP<br />Use convention over configuration<br />DRY: don’t repeat yourself<br />Separation of concerns<br />
  10. 10. The MVC pattern<br />
  11. 11. Separation of concerns<br />Separation of concerns comes naturally with MVC<br />Controller knows how to handle a request, that a View exist, and how to use the Model (no more)<br />Model doesn’t know anything about a View<br />View doesn’t know there is a Controller<br />
  12. 12. Asp.Net > Asp.Net MVC<br />Based on the .Net platform (quite straightforward  )<br />Master page<br />Forms authentication<br />Membership and Role providers<br />Profiles<br />Internationalization<br />Cache<br />Asp.Net MVC is built on (the best part of) Asp.Net<br />
  13. 13. Asp.Net and Asp.Net MVC run-time stack<br />
  14. 14. Demo<br />First Asp.NetMVC application<br />
  15. 15. Asp.Net MVC<br />The structure of the project<br />
  16. 16. Asp.Net MVC projects have some top-level (and core) directories that you don’t need to setup in the config:<br />Controllers, where you put the classes that handle the request<br />Models, where you put the classes that deal with data<br />Views, where you put the UI template files<br />Scripts, where you put Javascript library files and scripts (.js)<br />Content, where you put CSS and image files, and so on<br />App_Data, where you put data files<br />Convention over configuration<br />
  17. 17. Models, Controllers and Views<br />
  18. 18. The Models<br />Classes that represent your application data<br />Contain all the business, validation, and data acccess logic required by your application<br />Three different kind of Model: <br />data being posted on the Controller<br />data being worked on in the View<br />domain-specific entities from you business tier<br />You can create your own Data Model leveraging the most recommend data access technologies<br />The representation of our data<br />
  19. 19. An actual Data Model using Entity Framework 4.0<br />
  20. 20. ViewModel Pattern<br />Additional layer to abstract the data for the Views from our business tier<br />Can leverage the strongly typed View template features<br />The Controller has to know how to translate from the business tier Entity to the ViewModel one<br />Enable type safety, compile-time checking and Intellisense<br />Useful specially in same complex scenarios<br />Create a class tailored on our specific View scenarios<br />
  21. 21. publicActionResultCustomer(int id)<br />{<br />ViewData[“Customer”] = MyRepository.GetCustomerById(id);<br />ViewData[“Orders”] = MyRepository.GetOrderforCustomer(id);<br />return View();<br />}<br />publicclassCustomerOrderMV<br />{<br />Customer CustomerData {get; set;}<br />Order CustomerOrders{ get; set;}<br />}<br />publicActionResult Customer(int id)<br />{<br />CustomerOrderMVcustOrd = MyRepository.GetCustomerOrdersById(id);<br />ViewData.Model = custOrd;<br />return View();<br />}<br />Model vs.ViewModel<br />
  22. 22. Validation<br />Validation and business rule logic are the keys for any application that work with data<br />Schema validation comes quite free if you use OR/Ms<br />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)<br />Adding Validation Logic to the Models<br />
  23. 23. [MetadataType(typeof(Blog_Validation))]<br />publicpartialclassBlog<br />{<br />}<br />[Bind(Exclude = "IdBlog")]<br />publicclassBlog_Validation<br />{<br /> [Required(ErrorMessage= "Title required")]<br />[StringLength(50, ErrorMessage = "…")]<br />[DisplayName("Blog Title")]<br /> publicString Title { get; set; }<br />[Required(ErrorMessage = "Blogger required")]<br />[StringLength(50, ErrorMessage = “…")]<br />publicString Blogger { get; set; }ù<br />…<br />}<br />Data Annotations validation<br />How to add validation to the Model through Metadata<br />
  24. 24. Demo<br />Asp.Net MVC Models<br />
  25. 25. The controllers are responsible for responding to the user request<br />Have to implement at least the IController interface, but better if you use the ControllerBaseor the Controller abstract classes (with more API and resources, like the ControllerContext and the ViewData, to build your own Controller)<br />The Controllers<br />
  26. 26. using System;<br />usingSystem.Web.Routing;<br />namespaceSystem.Web.Mvc<br />{<br />// Summary:Defines the methods that are required for a controller.<br />publicinterfaceIController<br /> {<br />// Summary: Executes the specified request context.<br />// Parameters:<br />// requestContext:The request context.<br />void Execute(RequestContextrequestContext);<br /> }<br />}<br />usingSystem.Web;<br />usingSystem.Web.Mvc;<br />publicclassSteoController : IController<br />{<br />publicvoid Execute(System.Web.Routing.RequestContextrequestContext)<br /> {<br />HttpResponseBase response = requestContext.HttpContext.Response;<br />response.Write("<h1>Hello MVC World!</h1>");<br /> }<br />}<br />My own Controller<br />
  27. 27. publicinterfaceIHttpHandler<br />{<br />voidProcessRequest(HttpContext context);<br />boolIsReusable { get; }<br />}<br />publicinterfaceIController<br />{<br />voidExecute(RequestContextrequestContext);<br />}<br />They look quite similar, aren’t they?<br />The two methods respond to a request and write back the output to a response<br />The Page class, the default base class for ASPX pages in Asp.Net, implements the IHttpHandler.<br />This reminds me something…<br />
  28. 28. The Action Methods<br />All the public methods of a Controller class become Action methods, which are callable through an HTTP request<br />Actually, only the public methods according to the defined Routes can be called<br />
  29. 29. The ActionResult<br />Actions, as Controller’s methods, have to respond to user input, but they don’t have to manage how to display the output<br />The pattern for the Actions is to do their own work and then return an object that derives from the abstract base class ActionResult<br />ActionResultadhere to the “Command pattern”, in which commands are methods that you want the framework to perform in your behalf<br />
  30. 30. The ActionResult<br />publicabstract class ActionResult<br />{<br />public abstract voidExecuteResult(ControllerContext context);<br />}<br />publicActionResultList()<br />{<br />ViewData.Model= // get data from a repository<br />returnView();<br />}<br />
  31. 31. ActionResult types<br />EmptyResult<br />ContentResult<br />JsonResult<br />RedirectResult<br />RedirectToRouteResult<br />ViewResult<br />PartialViewResult<br />FileResult<br />FilePathResult<br />FileContentResult<br />FileStreamResult<br />JavaScriptResult<br />Asp.Net MVC has several types to help handle the response<br />
  32. 32. Demo<br />Asp.Net MVC Controllers<br />
  33. 33. The Views are responsible for providing the User Interface (UI) to the user<br />The View receive a reference to a Model and it transforms the data in a format ready to be presented<br />The Views<br />
  34. 34. Asp.Net MVC’s View<br />Handles the ViewDataDictionary and translate it into HTML code<br />It’s an Asp.Net Page, deriving from ViewPage (System.Web.Mvc.ViewPage) which itself derives from Page (System.Web.UI.Page)<br />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)<br />Can take advantage of the Master Page, building Views on top of the Asp.Net Page infrastructure<br />
  35. 35. Asp.Net MVC Views’ syntax<br />You will use <%: %> syntax (often referred to as “code nuggets”) to execute code within the View template.<br />There are two main ways you will see this used:<br />Code enclosed within <% %> will be executed<br />Code enclosed within <%: %> will be executed, and the result will be output to the page<br />
  36. 36. Demo<br />Views, Strongly Typed View, specify a View<br />
  37. 37. Html Helpers<br />Html.Encode<br />Html.TextBox<br />Html.ActionLink, RouteLink<br />Html.BeginForm<br />Html.Hidden<br />Html.DropDownList<br />Html.ListBox<br />Html.Password<br />Html.RadioButton<br />Html.Partial, RenderPartial<br />Html.Action, RenderAction<br />Html.TextArea<br />Html.ValidationMessage<br />Html.ValidationSummary<br />Methods shipped with Asp.Net MVC that help to deal with the HTML code.<br />MVC2 introduced also the strongly typed Helpers, that allow to use Model properties using a Lambda expression instead of a simple string<br />
  38. 38. Partial View<br />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)<br />The partial View has a .ascx extension and you can use like a HTML control <br />
  39. 39. The default Asp.Net MVC project just provide you a simple Partial View: the LogOnUserControl.ascx<br /><%@ControlLanguage="C#"Inherits="System.Web.Mvc.ViewUserControl" %><br /><%<br />if (Request.IsAuthenticated) {<br />%><br /> Welcome <b><%:Page.User.Identity.Name %></b>!<br /> [ <%:Html.ActionLink("Log Off", "LogOff", "Account") %> ]<br /><%<br /> }<br />else {<br />%> <br /> [ <%:Html.ActionLink("Log On", "LogOn", "Account") %> ]<br /><%<br /> }<br />%><br />Partial View Example<br />A simple example out of the box<br />
  40. 40. Ajax<br />You can use the most popular libraries: <br />Microsoft Asp.Net Ajax<br />jQuery<br />Can help to partial render a complex page (fit well with Partial View)<br />Each Ajax routine will use a dedicated Action on a Controller<br />With Asp.Net Ajax you can use the Ajax Helpers that come with Asp.Net MVC:<br />Ajax.BeginForm<br />AjaxOptions<br />IsAjaxRequest<br />…<br />It’s not really Asp.Net MVC but can really help you to boost your MVC application<br />
  41. 41. Routing<br />Routing in Asp.Net MVC are used to: <br />Match incoming requests and maps them to a Controller action<br />Construct an outgoing URLs that correspond to Contrller action<br />How Asp.Net MVC manages the URL<br />
  42. 42. Routing vs URL Rewriting<br />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<br />URL rewriting is a page centric view of URLs (eg: /products/redshoes.aspx rewritten as /products/display.aspx?productid=010)<br />Routing is a resource-centric (not only a page) view of URLs. You can look at Routing as a bidirectional URL rewriting<br />
  43. 43. publicstaticvoidRegisterRoutes(RouteCollection routes)<br />{<br />routes.IgnoreRoute("{resource}.axd/{*pathInfo}");<br />routes.MapRoute(<br />"Default", // Route name<br />"{controller}/{action}/{id}", // URL with parameters<br />new{ controller = "Home", action = "Index", id = UrlParameter.Optional} // Parameter defaults );<br />}<br /> protectedvoidApplication_Start()<br />{<br />AreaRegistration.RegisterAllAreas();<br />RegisterRoutes(RouteTable.Routes);<br />}<br />}<br />Defining Routes<br />The default one…<br />
  44. 44. Route URL patterns <br />
  45. 45. StopRoutingHandler and IgnoreRoute<br />You can use it when you don’t want to route some particular URLs.<br />Useful when you want to integrate an Asp.Net MVC application with some Asp.Net pages.<br />
  46. 46. Filters<br />Filters are declarative attribute based means of providing cross-cutting behavior <br />Out of the box action filters provided by Asp.Net MVC:<br />Authorize: to secure the Controller or a Controller Action<br />HandleError: the action will handle the exceptions<br />OutputCache: provide output caching to for the action methods<br />
  47. 47. Demo<br />A simple Filter (Session Expire)<br />
  48. 48. TDD with Asp.Net MVC<br />Asp.Net MVC was made with TDD in mind, but you can use also without it (if you want… )<br />A framework designed with TDD in mind from the first step<br />You can use your favorite Test Framework<br />With MVC you can test the also your UI behavior (!)<br />
  49. 49. Demo<br />TDD with Asp.Net MVC<br />
  50. 50. Let’s start the Open Session:Asp.Net vs. Asp.Net MVC<br />