0
MVC
A new Web Project Type for
ASP.NET.
An option.
More control over your <html/>
A more easily Testable
Framework.
Not for ev...
“ScottGu”
“The Gu”
“His Gu-ness”
“Sir”
“Master Chief Gu”
This is not Web Forms 4.0
  It’s about alternatives. Car vs. Motorcycle.
Flexible
  Extend it. Or not.
Fundamental
  Part ...
Maintain Clean Separation of Concerns
  Easy Testing
  Red/Green TDD
  Highly maintainable applications by default
Extensi...
Enable clean URLs and HTML
  SEO and REST friendly URL structures
Great integration within ASP.NET
  All the same provider...
MVC
Microsoft Visual Business
Enabler Studio 2008R3v2
September Technical
Preview Refresh
MSVBES2k8R3v2lptrczstr
for short
MVC




      27
Model




View           Controller
•Browser requests /Products/
       Model          •Route is determined
                      •Controller is activated
   ...
• You can futz at each step
Request
             in the process


 HTTP      Http
                      Controller   Respo...
MVC
Developers adds Routes to a global RouteTable
   Mapping creates a RouteData - a bag of key/values
RouteTable.Routes.Add(
...
Views
Controllers
Models
Routes

…are all Pluggable
View Engines render output
You get WebForms by default
Can implement your own
  MVCContrib has ones for Brail, Nvelocity
 ...
ViewEngineBase
public abstract class ViewEngineBase {
    public abstract void RenderView(ViewContext viewContext);
}
<%@ Page Language=quot;C#quot; MasterPageFile=quot;~/Views/Shared/Site.Masterquot;
   AutoEventWireup=quot;truequot;
    C...
%h2= ViewData.CategoryName
  %ul
    - foreach (var product in ViewData.Products)
    %li = product.ProductName
      .edi...
MVC
Mockable Intrinsics
  HttpContextBase,
  HttpResponseBase,
  HttpRequestBase
Extensibility
  IController
  IControllerFact...
No requirement to test within ASP.NET runtime.
        Use RhinoMocks or TypeMock
        Create Test versions of the part...
This is not Web Forms 4.0
  It’s about alternatives. Car vs. Motorcycle.
Flexible
  Extend it. Or not.
Fundamental
  Part ...
HAI!
IM IN YR Northwind
HOW DUZ I ListProducts YR id
PRODUCTS = GETPRODUCTS id
OMG FOUND YR PRODUCTS
IF U SEZ
IM OUTTA YR ...
HAI!
WTF:
I HAS A STRING
GIMMEH STRING
IM IN YR VAR UPPIN YR 0
   TIL LENGTH OF STRING
VISIBLE “GIMMEE A ” STRING!!VAR
STE...
© 2008 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be...
MVC
Base Controller Class
   Basic Functionality most folks will use
IController Interface
   Ultimate Control for the Control...
Scenarios, Goals and Design
    URLs route to controller “actions”, not pages –
    mark actions in Controller.
    Contro...
public class Controller : IController {
   …
   protected virtual void Execute(ControllerContext
   controllerContext);
  ...
public class Controller : IController {
    …
    protected virtual void Execute(ControllerContext
   controllerContext);
...
public class Controller : IController {
    …
    protected virtual void Execute(ControllerContext
   controllerContext);
...
public class Controller : IController {
  …
  protected virtual void Execute(ControllerContext
   controllerContext);
  pr...
Scenarios, Goals and Design:
  Are for rendering/output.
   Pre-defined and extensible rendering helpers
  Can use .ASPX, ...
View Engines render output
You get WebForms by default
Can implement your own
  MVCContrib has ones for Brail, Nvelocity
 ...
ViewEngineBase
public abstract class ViewEngineBase {
    public abstract void RenderView(ViewContext viewContext);
}
<%@ Page Language=quot;C#quot; MasterPageFile=quot;~/Views/Shared/Site.Masterquot;
   AutoEventWireup=quot;truequot;
    C...
%h2= ViewData.CategoryName
  %ul
    - foreach (var product in ViewData.Products)
    %li = product.ProductName
      .edi...
Scenarios, Goals and Design:
      Hook creation of controller instance
         Dependency Injection.
         Object Int...
Scenarios, Goals and Design:
     Mock out views for testing
     Replace ASPX with other technologies
public interface IV...
Developing ASP.NET Applications Using the Model View Controller Pattern
Developing ASP.NET Applications Using the Model View Controller Pattern
Developing ASP.NET Applications Using the Model View Controller Pattern
Developing ASP.NET Applications Using the Model View Controller Pattern
Developing ASP.NET Applications Using the Model View Controller Pattern
Developing ASP.NET Applications Using the Model View Controller Pattern
Developing ASP.NET Applications Using the Model View Controller Pattern
Developing ASP.NET Applications Using the Model View Controller Pattern
Developing ASP.NET Applications Using the Model View Controller Pattern
Developing ASP.NET Applications Using the Model View Controller Pattern
Developing ASP.NET Applications Using the Model View Controller Pattern
Developing ASP.NET Applications Using the Model View Controller Pattern
Developing ASP.NET Applications Using the Model View Controller Pattern
Developing ASP.NET Applications Using the Model View Controller Pattern
Developing ASP.NET Applications Using the Model View Controller Pattern
Developing ASP.NET Applications Using the Model View Controller Pattern
Developing ASP.NET Applications Using the Model View Controller Pattern
Developing ASP.NET Applications Using the Model View Controller Pattern
Developing ASP.NET Applications Using the Model View Controller Pattern
Developing ASP.NET Applications Using the Model View Controller Pattern
Developing ASP.NET Applications Using the Model View Controller Pattern
Developing ASP.NET Applications Using the Model View Controller Pattern
Upcoming SlideShare
Loading in...5
×

Developing ASP.NET Applications Using the Model View Controller Pattern

4,176

Published on

Learn how to use the model-view-controller (MVC) pattern to take advantage of your favorite .NET Framework language for writing business logic in a way that is de-coupled from the views of the data.

Published in: Technology
0 Comments
3 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
4,176
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
197
Comments
0
Likes
3
Embeds 0
No embeds

No notes for slide

Transcript of "Developing ASP.NET Applications Using the Model View Controller Pattern"

  1. 1. MVC
  2. 2. A new Web Project Type for ASP.NET. An option. More control over your <html/> A more easily Testable Framework. Not for everyone.
  3. 3. “ScottGu”
  4. 4. “The Gu”
  5. 5. “His Gu-ness”
  6. 6. “Sir”
  7. 7. “Master Chief Gu”
  8. 8. This is not Web Forms 4.0 It’s about alternatives. Car vs. Motorcycle. Flexible Extend it. Or not. Fundamental Part of System.Web and isn’t going anywhere. Plays Well With Others Feel free to use NHibernate for Models, Brail for Views and Whatever for Controllers. Keep it simple and DRY
  9. 9. Maintain Clean Separation of Concerns Easy Testing Red/Green TDD Highly maintainable applications by default Extensible and Pluggable Support replacing any component of the system
  10. 10. Enable clean URLs and HTML SEO and REST friendly URL structures Great integration within ASP.NET All the same providers still work Membership, Session, Caching, etc. ASP.NET Designer Surface in VS2008
  11. 11. MVC
  12. 12. Microsoft Visual Business Enabler Studio 2008R3v2 September Technical Preview Refresh MSVBES2k8R3v2lptrczstr for short
  13. 13. MVC 27
  14. 14. Model View Controller
  15. 15. •Browser requests /Products/ Model •Route is determined •Controller is activated •Method on Controller is invoke •Controller does some stuff •Renders View, passing in custom ViewData •URLs are rendered, pointing to other View Controller Controllers
  16. 16. • You can futz at each step Request in the process HTTP Http Controller Response Routing Handler Route View Route View Handler Engine
  17. 17. MVC
  18. 18. Developers adds Routes to a global RouteTable Mapping creates a RouteData - a bag of key/values RouteTable.Routes.Add( new Route(quot;blog/bydate/{year}/{month}/{day}quot;, new MvcRouteHandler()){ Defaults = new RouteValueDictionary { {quot;controllerquot;, quot;blogquot;}, {quot;actionquot;, quot;showquot;} }, Constraints = new RouteValueDictionary { {quot;yearquot;, @quot;d{1.4}quot;}, {quot;monthquot;, @quot;d{1.2}quot;}, {quot;dayquot;, @quot;d{1.2}quot;}} })
  19. 19. Views Controllers Models Routes …are all Pluggable
  20. 20. View Engines render output You get WebForms by default Can implement your own MVCContrib has ones for Brail, Nvelocity NHaml is an interesting one to watch View Engines can be used to Offer new DSLs to make HTML easier Generate totally different mime/types Images, RSS, JSON, XML, OFX, VCards, whatever.
  21. 21. ViewEngineBase public abstract class ViewEngineBase { public abstract void RenderView(ViewContext viewContext); }
  22. 22. <%@ Page Language=quot;C#quot; MasterPageFile=quot;~/Views/Shared/Site.Masterquot; AutoEventWireup=quot;truequot; CodeBehind=quot;List.aspxquot; Inherits=quot;MvcApplication5.Views.Products.Listquot; Title=quot;Productsquot; %> <asp:Content ContentPlaceHolderID=quot;MainContentPlaceHolderquot; runat=quot;serverquot;> <h2><%= ViewData.CategoryName %></h2> <ul> <% foreach (var product in ViewData.Products) { %> <li> <%= product.ProductName %> <div class=quot;editlinkquot;> (<%= Html.ActionLink(quot;Editquot;, new { Action=quot;Editquot;, ID=product.ProductID })%>) </div> </li> <% } %> </ul> <%= Html.ActionLink(quot;Add New Productquot;, new { Action=quot;Newquot; }) %> </asp:Content>
  23. 23. %h2= ViewData.CategoryName %ul - foreach (var product in ViewData.Products) %li = product.ProductName .editlink = Html.ActionLink(quot;Editquot;, new { Action=quot;Editquot;, ID=product.ProductID }) = Html.ActionLink(quot;Add New Productquot;, new { Action=quot;Newquot; })
  24. 24. MVC
  25. 25. Mockable Intrinsics HttpContextBase, HttpResponseBase, HttpRequestBase Extensibility IController IControllerFactory IRouteHandler ViewEngineBase
  26. 26. No requirement to test within ASP.NET runtime. Use RhinoMocks or TypeMock Create Test versions of the parts of the runtime you want to stub [TestMethod] public void ShowPostsDisplayPostView() { TestPostRepository repository = new TestPostRepository(); TestViewEngine viewEngine = new TestViewEngine(); BlogController controller = new BlogController(…); controller.ShowPost(2); Assert.AreEqual(quot;showpostquot;,viewEngine.LastRequestedView); Assert.IsTrue(repository.GetPostByIdWasCalled); Assert.AreEqual(2, repository.LastRequestedPostId); }
  27. 27. This is not Web Forms 4.0 It’s about alternatives. Car vs. Motorcycle. Flexible Extend it. Or not. Fundamental Part of System.Web and isn’t going anywhere. Plays Well With Others Feel free to use NHibernate for Models, Brail for Views and Whatever for Controllers. Keep it simple and DRY
  28. 28. HAI! IM IN YR Northwind HOW DUZ I ListProducts YR id PRODUCTS = GETPRODUCTS id OMG FOUND YR PRODUCTS IF U SEZ IM OUTTA YR Northwind
  29. 29. HAI! WTF: I HAS A STRING GIMMEH STRING IM IN YR VAR UPPIN YR 0 TIL LENGTH OF STRING VISIBLE “GIMMEE A ” STRING!!VAR STEPPIN IM OUTTA YR VAR OMGWTF HALP!
  30. 30. © 2008 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.
  31. 31. MVC
  32. 32. Base Controller Class Basic Functionality most folks will use IController Interface Ultimate Control for the Control Freak IControllerFactory For plugging in your own stuff (IOC, etc)
  33. 33. Scenarios, Goals and Design URLs route to controller “actions”, not pages – mark actions in Controller. Controller executes logic, chooses view. All public methods are accessible public void ShowPost(int id) { Post p = PostRepository.GetPostById(id); if (p != null) { RenderView(quot;showpostquot;, p); } else { RenderView(quot;nosuchpostquot;, id); } }
  34. 34. public class Controller : IController { … protected virtual void Execute(ControllerContext controllerContext); protected virtual void HandleUnknownAction(string actionName); protected virtual bool InvokeAction(string actionName); protected virtual void InvokeActionMethod(MethodInfo methodInfo); protected virtual bool OnError(string actionName, MethodInfo methodInfo, Exception exception); protected virtual void OnActionExecuted(FilterExecutedContext filterContext); protected virtual bool OnActionExecuting(FilterExecutedContext filterContext); protected virtual void RedirectToAction(object values); protected virtual void RenderView(string viewName, string masterName, object viewData); }
  35. 35. public class Controller : IController { … protected virtual void Execute(ControllerContext controllerContext); protected virtual void HandleUnknownAction(string actionName); protected virtual bool InvokeAction(string actionName); protected virtual void InvokeActionMethod(MethodInfo methodInfo); protected virtual bool OnError(string actionName, MethodInfo methodInfo, Exception exception); protected virtual void OnActionExecuted(FilterExecutedContext filterContext); protected virtual bool OnActionExecuting(FilterExecutedContext filterContext); protected virtual void RedirectToAction(object values); protected virtual void RenderView(string viewName, string masterName, object viewData); }
  36. 36. public class Controller : IController { … protected virtual void Execute(ControllerContext controllerContext); protected virtual void HandleUnknownAction(string actionName); protected virtual bool InvokeAction(string actionName); protected virtual void InvokeActionMethod(MethodInfo methodInfo); protected virtual bool OnError(string actionName, MethodInfo methodInfo, Exception exception); protected virtual void OnActionExecuted(FilterExecutedContext filterContext); protected virtual bool OnActionExecuting(FilterExecutedContext filterContext); protected virtual void RedirectToAction(object values); protected virtual void RenderView(string viewName, string masterName, object viewData); }
  37. 37. public class Controller : IController { … protected virtual void Execute(ControllerContext controllerContext); protected virtual void HandleUnknownAction(string actionName); protected virtual bool InvokeAction(string actionName); protected virtual void InvokeActionMethod(MethodInfo methodInfo); protected virtual bool OnError(string actionName, MethodInfo methodInfo, Exception exception); protected virtual void OnActionExecuted(FilterExecutedContext filterContext); protected virtual bool OnActionExecuting(FilterExecutedContext filterContext); protected virtual void RedirectToAction(object values); protected virtual void RenderView(string viewName, string masterName, object viewData); }
  38. 38. Scenarios, Goals and Design: Are for rendering/output. Pre-defined and extensible rendering helpers Can use .ASPX, .ASCX, .MASTER, etc. Can replace with other view technologies: Template engines (NVelocity, Brail, …). Output formats (images, RSS, JSON, …). Mock out for testing. Controller sets data on the View Loosely typed or strongly typed data
  39. 39. View Engines render output You get WebForms by default Can implement your own MVCContrib has ones for Brail, Nvelocity NHaml is an interesting one to watch View Engines can be used to Offer new DSLs to make HTML easier to write Generate totally different mime/types Images RSS, JSON, XML, OFX, etc. VCards, whatever.
  40. 40. ViewEngineBase public abstract class ViewEngineBase { public abstract void RenderView(ViewContext viewContext); }
  41. 41. <%@ Page Language=quot;C#quot; MasterPageFile=quot;~/Views/Shared/Site.Masterquot; AutoEventWireup=quot;truequot; CodeBehind=quot;List.aspxquot; Inherits=quot;MvcApplication5.Views.Products.Listquot; Title=quot;Productsquot; <asp:Content ContentPlaceHolderID=quot;MainContentPlaceHolderquot; runat=quot;serverquot;> <h2><%= ViewData.CategoryName %></h2> <ul> <% foreach (var product in ViewData.Products) { %> <li> <%= product.ProductName %> <div class=quot;editlinkquot;> (<%= Html.ActionLink(quot;Editquot;, new { Action=quot;Editquot;, ID=product.ProductID })%>) </div> </li> <% } %> </ul> <%= Html.ActionLink(quot;Add New Productquot;, new { Action=quot;Newquot; }) %> </asp:Content>
  42. 42. %h2= ViewData.CategoryName %ul - foreach (var product in ViewData.Products) %li = product.ProductName .editlink = Html.ActionLink(quot;Editquot;, new { Action=quot;Editquot;, ID=product.ProductID }) = Html.ActionLink(quot;Add New Productquot;, new { Action=quot;Newquot; })
  43. 43. Scenarios, Goals and Design: Hook creation of controller instance Dependency Injection. Object Interception. public interface IControllerFactory { IController CreateController(RequestContext context, string controllerName); } protected void Application_Start(object s, EventArgs e) { ControllerBuilder.Current.SetControllerFactory( typeof(MyControllerFactory)); }
  44. 44. Scenarios, Goals and Design: Mock out views for testing Replace ASPX with other technologies public interface IViewEngine { void RenderView(ViewContext context); } Inside controller class: this.ViewEngine = new XmlViewEngine(...); RenderView(quot;fooquot;, myData);
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×