Introduction To ASP.NET MVC

9,105 views

Published on

Published in: Technology
1 Comment
4 Likes
Statistics
Notes
No Downloads
Views
Total views
9,105
On SlideShare
0
From Embeds
0
Number of Embeds
2,222
Actions
Shares
0
Downloads
281
Comments
1
Likes
4
Embeds 0
No embeds

No notes for slide

Introduction To ASP.NET MVC

  1. 1. The ASP.NET MVC Framework<br />Jess Chadwick<br />Independent Consultant<br />Microsoft MVP, ASPInsider<br />
  2. 2. We thank the following companies for their gracious sponsorship<br />Platinum Sponsors<br />Gold Sponsor<br />
  3. 3. Agenda<br />What is ASP.NET MVC?<br />Overview / Goals<br />Quick demo<br />The Pattern<br />AJAX-ifying your MVC app<br />Testability<br />Advanced Features<br />
  4. 4. What is ASP.NET MVC?<br />Microsoft’s ASP.NET implementation of the MVC software pattern<br />More control over your HTML and URLs<br />More easily testable framework<br />A new Web Project type for ASP.NET<br />An option / alternative<br />
  5. 5. DEMO: MVC Hello World<br />Let’s whet the appetite!<br />
  6. 6. What’s the Point?<br />This is not “Web Forms v.Next”<br />All about alternatives<br />Flexibility<br />Extend it… or not<br />Create your own Controller- and View- Engines or use others such as Brail or NHaml<br />Fundamental<br />Part of System.Web namespace<br />Fully supported<br />KISS & DRY<br />
  7. 7. Driving Goals<br />Separation of Concerns<br />Easy testing & TDD<br />Highly-maintainable applications<br />Extensible and Pluggable<br />Plug in what you need<br />Build your own custom build<br />
  8. 8. Driving Goals (cont’d)<br />Clean URLs and HTML<br />SEO and REST friendly<br />Great interaction with ASP.NET<br />Handlers, Modules, Providers, etc. still work<br />.ASPX, .ASCX, .MASTER pages<br />Visual Studio ASP.NET Designer surface<br />
  9. 9. So, what is it?<br />
  10. 10. The Pattern<br />
  11. 11. The Model<br />“The center of the universe”<br />This represents your core business domain…AKA – your “bread and butter”<br />Preferably independent of any specific technology<br />
  12. 12. Views<br /><ul><li>Are for rendering/output.
  13. 13. Are pretty “stupid”
  14. 14. Web Forms as default ViewEngine
  15. 15. .ASPX, .ASCX, .MASTER, etc.
  16. 16. Html Helpers for rendering markup
  17. 17. Can replace with other view technologies:
  18. 18. Template engines (NVelocity, Brail, …).
  19. 19. Output formats (images, RSS, JSON, …).
  20. 20. Mock out for testing.
  21. 21. Can use loosely typed or strongly typed data</li></li></ul><li>Controllers<br />URLs route to actions on controllers, not pages<br />Controller executes logic, loads data (if any), and chooses view.<br />Can also redirect to other views & URLs<br />public ActionResultShowPost(int id) {<br /> Post p = PostRepository.GetPostById(id);<br /> if (p == null) {<br /> return View("nosuchpost", id);<br /> } else {<br /> return View(“showpost", p);<br /> }<br />}<br />
  22. 22. ASP.NET MVC vs. Web Forms<br />Data<br />View(ASPX)--------------Controller<br />(Code-Behind)<br />ASP.NET Web Forms (Page Controller)<br />Model<br />List View<br />Detail View<br />Product Controller<br />ASP.NET MVC <br />(Front Controller)<br />Data<br />Model<br />
  23. 23. The MVC Pattern in action<br /><ul><li>Browser makes a request
  24. 24. Route is determined
  25. 25. Controller is activated
  26. 26. Method (Action) on Controller is invoked
  27. 27. Controller does some stuff
  28. 28. Renders View, passing in custom ViewData
  29. 29. URLs are rendered, pointing to other Controllers</li></li></ul><li>Request Flow<br />
  30. 30. URL Routing<br />Developers add Routes to a global RouteTable<br />Mapping creates a RouteData - a bag of key/values<br />routes.MapRoute(<br /> "blog/bydate/{year}/{month}/{day}", new { controller = “blog”, action = “show” },<br /> Constraints = new RouteValueDictionary { {"year", @"d{1.4}"}, {"month", @"d{1.2}"},<br /> {"day", @"d{1.2}"}}<br /> })<br />
  31. 31. URL Routing (cont’d)<br />Separate assembly, not closely tied/related to ASP.NET MVC<br />
  32. 32. DEMO: Online Catalog Sample<br />
  33. 33. Using ASP.NET MVC to Create Rich Web Experiences<br />I don’t care if “Web 2.0” is a cliché!<br />
  34. 34. ASP.NET MVC: User Controls<br />Isolate reusable view components<br />(Not the logic to retrieve the data!)<br />
  35. 35. DEMO<br />Adding User Controlsto Your Views<br />This should be nothing new, but it does prepare us for bigger and better things…<br />
  36. 36. ASP.NET MVC: Partial Rendering<br />You can render user controls:<br />As part of a page, or…<br />Down the wire by themselves!<br />
  37. 37. DEMO: AJAX-ifying the Online Catalog Sample<br />
  38. 38. Testability<br />“What!? I can mock out HttpContext!?”<br />
  39. 39. Designed for Testability<br />MockableIntrinsics<br />HttpContextBase, HttpResponseBase, HttpRequestBase<br />Extensibility <br />IController<br />IControllerFactory<br />IRouteHandler<br />ViewEngineBase<br />
  40. 40. Testing Controller Actions<br />No requirement to test within ASP.NET runtime!<br />Use RhinoMocks, TypeMock, Moq, etc.<br />Create Test versions of the parts of the runtime you want to stub<br />[TestMethod]<br />public void ShowPostsDisplayPostView() {<br />TestPostRepository repository = new TestPostRepository();<br />TestViewEngineviewEngine = new TestViewEngine();<br />BlogController controller = new BlogController(…);<br />var result = controller.ShowPost(2) as ViewResult;<br />Assert.AreEqual("showpost",result.ViewName);<br />Assert.IsTrue(repository.GetPostByIdWasCalled);<br />Assert.AreEqual(2, repository.LastRequestedPostId);<br />}<br />
  41. 41. DEMO: Test-Driven Development<br />“Wasn’t this supposed to come first?”<br />
  42. 42. Advanced ASP.NET MVC Features<br /><ul><li> Filters
  43. 43. Extensibility
  44. 44. View Engines
  45. 45. Controller Factories
  46. 46. Routing Handler</li></li></ul><li>Filters<br />Add pre- and post-execute behaviors to your controller actions<br />Useful for logging, compression, etc.<br />public abstract class ActionFilterAttribute<br />{<br />public void OnActionExecuting(ActionExecutingContext context) ;<br /> public void OnActionExecuted(ActionExecutingContext context) ;<br /> // New in Pre-Preview 3:<br /> public void OnResultExecuting(ResultExecutingContext context);<br /> public void OnResultExecuted(ResultExecutedContext context);<br />}<br />
  47. 47. Extensibility<br />Views<br />Controllers<br />Models<br />Routes<br />…all Pluggable<br />
  48. 48. ViewEngineBase<br />View Engines render output<br />You get WebForms by default<br />Can implement your own<br />MVCContrib has ones for Brail, Nvelocity<br />NHaml is an interesting one to watch<br />View Engines can be used to<br />Offer new DSLs to make HTML easier<br />Generate totally different mime/types<br />Images, RSS, JSON, XML, OFX, VCards, whatever.<br />
  49. 49. Example View: Web Forms<br /><%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" AutoEventWireup="true" <br />CodeBehind="List.aspx" Inherits="MvcApplication5.Views.Products.List" Title="Products" %><br /><asp:ContentContentPlaceHolderID="MainContentPlaceHolder" runat="server"><br /> <h2><%= ViewData.CategoryName %></h2><br /> <ul><br /> <% foreach (var product in ViewData.Products) { %><br /> <li><br /> <%= product.ProductName %> <br /> <div class="editlink"><br /> (<%= Html.ActionLink("Edit", new { Action="Edit", ID=product.ProductID })%>)<br /> </div><br /> </li><br /> <% } %><br /> </ul><br /> <%= Html.ActionLink("Add New Product", new { Action="New" }) %><br /></asp:Content><br />
  50. 50. Example View: NHaml<br />%h2= ViewData.CategoryName%ul<br /> - foreach (var product in ViewData.Products) %li = product.ProductName .editlink = Html.ActionLink("Edit", new { Action="Edit", ID=product.ProductID }) = Html.ActionLink("Add New Product", new { Action="New" })<br />
  51. 51. Example View: Spark<br /><h2>${CategoryName}</h2><br /><viewdata products="IEnumerable[[Product]]"/><br /><ul if="products.Any()"><br /> <li each="var p in products">${p.Name}</li><br /></ul><br /><else><br /> <p>No products available</p><br /></else><br />
  52. 52. Demo: Filters and View Engines<br />Now we can really take control!<br />
  53. 53. What’s the Point?<br />This is not “Web Forms v.Next”<br />All about alternatives<br />Flexibility<br />Extend it… or not<br />Create your own Controller- and ViewEngines, or use others such as Brail or NHaml<br />Fundamental<br />Part of System.Web namespace<br />Fully supported<br />KISS & DRY<br />
  54. 54. Questions?<br />
  55. 55. Relevant Sessions Today<br />Extending ASP.NET MVC w/ MVCContribJohn Zablocki Noon – 1 PM<br />Ignite Your MVC Application with Spark View EngineCurtis Mitchell 4PM – 5:15 PM<br />
  56. 56. Resources<br /> The Bits<br /> ASP.NET MVC: http://asp.net/MVC<br />MVCContrib: http://www.codeplex.com/MVCContrib<br />Quickstart<br /> http://quickstarts.asp.net/3-5-extensions/mvc/default.aspx<br /> Videos<br /> ASP.NET: http://www.asp.net/learn/3.5-extensions-videos/<br /> MIX: http://sessions.visitmix.com<br /> Community/Blogs<br /> ASP.NET Forums: http://forums.asp.net/1146.aspx<br /> Scott Guthrie (ScottGu): http://weblogs.asp.net/scottgu/<br /> Scott Hanselman: http://www.hanselman.com/blog/<br /> Phil Haack: http://haacked.com/<br /> Sample Apps<br /> MVC Samples: http://www.codeplex.com/mvcsamples<br />CodeCampServer: http://codecampserver.org<br />Jess Chadwick<br />Independent Consultant<br />Microsoft MVP, ASPInsider<br />jesschadwick@gmail.com<br />http://blog.jesschadwick.com<br />

×