Introduction to ASP.NET MVC Adnan Masood Volkan Uzun www.CodePlex.com/YABE
About Adnan aka. Shameless Self Promotion Sr. Software Engineer / Tech Lead for Green Dot Corp. (Financial Institution) Design and Develop Connected Systems. Involved with SoCal Dev community, co-founded San Gabriel Valley .NET Developers Group. Published author and speaker. Winner of 2008-2009 Developer Community Champion Award. MS. Computer Science, MCPD (Enterprise Developer), MCT, MCSD.NET Doctoral Student - Areas of Interest: Machine learning, Bayesian Inference, Data Mining, Collaborative Filtering, Recommender Systems. Contact at adnanmasood@acm.org Read my Blog at  www.AdnanMasood.com REST and WCF 3.5 – Geek Speak Webcast Doing a session in IASA 2008 in San Francisco on Aspect Oriented Programming; for details visit http://www.iasaconnections.com
About Me Web Developer at California State University, San Bernardino Developing campus web sites, online courses, databases, securing the systems, making the sites accessible according 508 Guidelines Active member of Inland Empire .NET user group User group freak, attending average 5/6 users groups a month, driving 1000 miles average extra. MS Computer Science, MCTS Sql Server 2005, MCP ASP.NET 2.0 2007-2008 Most Valuable member of Inland Empire .NET user group Not so active blog: http://msnetprogrammer.net/blog Trying to write better code by applying TDD (newbie!), reading other developers’ code (Scott Hanselman’s idea) Lifetime learner Email: volkan.uzun@gmail.com
Agenda 1. Introduction to MVC 2. Building your first MVC application  (demo) 3. Understanding Controllers, Controller Actions, and Action Results 4. Understanding Models, Views, and Controllers 5. How to do Routing (demo) 6. How to do unit testing (demo) 7. How does YABE work (code walkthrough and demo) 8. Brief discussion of dependency injection et al
Top 5 MVC Resources ASP.NET MVC Home ( www.asp.net/mvc ) Scott Guthrie’s Weblog  (www.weblogs.asp.net/Scottgu) Scott Hanselman’s Blog ( http://www.hanselman.com/blog/ ) Phil Haack ( http://haacked.com/Tags/aspnetmvc/default.aspx ) ASP.NET Quick Start (http://quickstarts.asp.net/3-5-extensions/mvc/default.aspx)
ASP.NET MVC in a nutshell ASP.NET MVC enables you to build Model View Controller (MVC) applications by using the ASP.NET framework. ASP.NET MVC is an alternative, not a replacement, for ASP.NET Web Forms that offers the following benefits:  Clear separation of concerns  Testability - support for Test-Driven Development Fine-grained control over HTML and JavaScript Intuitive URLs
Highlights & Latest Developments in the MVC world MVC Beta has been released Jquery will be coming with MVC Beta More TDD support Some functions are carried over between dll’s
MVC vs. “Classic” ASP.NET
Model View Controller Pattern
Why MVC? Very Clean separation of Concerns  Inherent Unit Testing Support Model that leads you down a maintainable path (helps writing better code but doesn’t stop you writing crappy code) Clean Urls and Html
Features Routing Controller View Dependency Injection Pluggable Interfaces for all core contracts
DEMO Build your first ASP.NET MVC APP
MVC? A very brief explanation is: Model: Your data source; database, text file, web services etc View: Html page, what client sees Controller: CPU of the mechanism, gets request from web server, communicates with Model to get data, returns a view to the requestor. A url request is a function inside controller class
Url Url no longer points to the view/aspx page A Url maps to a controller class Allows more flexibility to map Urls Url routing engine, Route table Routes are tokenized strings Can use RegEx
Controllers & Actions Responds to requests Interacts with Model, and renders Views All controllers should have suffix “Controller” Derives from System.Web.MVC.Controller class   At the end, it is just a class, that has functions => Controller Actions that can’t be static, returns ActionResult
ActionResult & Actions Controller Actions return ActionResult ActionResult can be: ViewResult – Represents HTML and markup. EmptyResult – Represents no result. RedirectResult – Represents a redirection to a new URL. RedirectToRouteResult – Represents a redirection to a new controller action. JsonResult – Represents a JavaScript Object Notation result that can be used in an AJAX application. ContentResult – Represents a text result. Custom ActionResult
Model, View, Controller Controller: Gets the request from the requestor, (route mapping happens here), fires the action depending on the request ActionMethod: communicates with Model to get the data returns ActionResult ActionMethod can use ViewData, ViewData.Model or TempData to send data to View View generates the markup language for the requestor. View can use strongly typed Model
Views Similar to existing page No postback or view state Not all page events will fire Editing forms will be more work Separate page for viewing, editing, and updating Ajax will use UserControls as update panels but request still goes through the control
Views View probably shouldn’t directly access data sources or services. You should put the business logic inside the views; try to stay away from <%if … Use the ViewData which stores the model the  view is rendering ViewPage<T>, ViewPage No postback
DEMO Add a new controller Test, with model interaction
How much backward Compatibility is there? The MVC framework supports using the existing ASP.NET .ASPX, .ASCX, and .Master markup files as &quot;view templates&quot; (meaning you can easily use existing ASP.NET features like nested master pages, <%= %> snippets, declarative server controls, templates, data-binding, localization, etc).  It does not, however, use the existing post-back model for interactions back to the server.  Instead, you'll route all end-user interactions to a Controller class instead - which helps ensure clean separation of concerns and testability (it also means no viewstate or page lifecycle with MVC based views). The ASP.NET MVC framework fully supports existing ASP.NET features like forms/windows authentication, URL authorization, membership/roles, output and data caching, session/profile state management, health monitoring, configuration system, the provider architecture, etc.
URL Routing URL Routing is mapping the incoming requests to controller’s action methods. There are handler’s settings in the web.config Routing table exists in Global.asax.cs Application_Start() registers the routing table You can use regex to define route mappings Route mapping works top to bottom, first match is called Download Phil Hack’s RouteDebug tool
Route Examples <Controller>/<Action>/<Param> http://domain/ Home/CustomerDetail/45 Html.Link for creating outbound urls Html.Link(<Friendly Name>, <Action>, <Controller>)
DEMO Add a new controller action , set the route
Unit Testing Mock Objects to simulate responses. Don’t have to go through a page or view Red/Green Testing Create instance of controller Uses Mock Objects You will need depedency injection down the road
Future of ASP.NET MVC MVC for the Enterprise Classic Asp.Net for quicker implementations
References Download the Latest MVC Beta from Codeplex Quick Start Guides http://quickstarts.asp.net/3-5-extensions/mvc/default.aspx
Questions? ASP.NET MVC is a new paradigm for .NET Developers; a new way to think about programming web application. Any Questions / Comments … feel free to contact  [email_address]   Visit  www.CodePlex.com/YABE

Introduction To Mvc

  • 1.
    Introduction to ASP.NETMVC Adnan Masood Volkan Uzun www.CodePlex.com/YABE
  • 2.
    About Adnan aka.Shameless Self Promotion Sr. Software Engineer / Tech Lead for Green Dot Corp. (Financial Institution) Design and Develop Connected Systems. Involved with SoCal Dev community, co-founded San Gabriel Valley .NET Developers Group. Published author and speaker. Winner of 2008-2009 Developer Community Champion Award. MS. Computer Science, MCPD (Enterprise Developer), MCT, MCSD.NET Doctoral Student - Areas of Interest: Machine learning, Bayesian Inference, Data Mining, Collaborative Filtering, Recommender Systems. Contact at adnanmasood@acm.org Read my Blog at www.AdnanMasood.com REST and WCF 3.5 – Geek Speak Webcast Doing a session in IASA 2008 in San Francisco on Aspect Oriented Programming; for details visit http://www.iasaconnections.com
  • 3.
    About Me WebDeveloper at California State University, San Bernardino Developing campus web sites, online courses, databases, securing the systems, making the sites accessible according 508 Guidelines Active member of Inland Empire .NET user group User group freak, attending average 5/6 users groups a month, driving 1000 miles average extra. MS Computer Science, MCTS Sql Server 2005, MCP ASP.NET 2.0 2007-2008 Most Valuable member of Inland Empire .NET user group Not so active blog: http://msnetprogrammer.net/blog Trying to write better code by applying TDD (newbie!), reading other developers’ code (Scott Hanselman’s idea) Lifetime learner Email: volkan.uzun@gmail.com
  • 4.
    Agenda 1. Introductionto MVC 2. Building your first MVC application (demo) 3. Understanding Controllers, Controller Actions, and Action Results 4. Understanding Models, Views, and Controllers 5. How to do Routing (demo) 6. How to do unit testing (demo) 7. How does YABE work (code walkthrough and demo) 8. Brief discussion of dependency injection et al
  • 5.
    Top 5 MVCResources ASP.NET MVC Home ( www.asp.net/mvc ) Scott Guthrie’s Weblog (www.weblogs.asp.net/Scottgu) Scott Hanselman’s Blog ( http://www.hanselman.com/blog/ ) Phil Haack ( http://haacked.com/Tags/aspnetmvc/default.aspx ) ASP.NET Quick Start (http://quickstarts.asp.net/3-5-extensions/mvc/default.aspx)
  • 6.
    ASP.NET MVC ina nutshell ASP.NET MVC enables you to build Model View Controller (MVC) applications by using the ASP.NET framework. ASP.NET MVC is an alternative, not a replacement, for ASP.NET Web Forms that offers the following benefits: Clear separation of concerns Testability - support for Test-Driven Development Fine-grained control over HTML and JavaScript Intuitive URLs
  • 7.
    Highlights & LatestDevelopments in the MVC world MVC Beta has been released Jquery will be coming with MVC Beta More TDD support Some functions are carried over between dll’s
  • 8.
  • 9.
  • 10.
    Why MVC? VeryClean separation of Concerns Inherent Unit Testing Support Model that leads you down a maintainable path (helps writing better code but doesn’t stop you writing crappy code) Clean Urls and Html
  • 11.
    Features Routing ControllerView Dependency Injection Pluggable Interfaces for all core contracts
  • 12.
    DEMO Build yourfirst ASP.NET MVC APP
  • 13.
    MVC? A verybrief explanation is: Model: Your data source; database, text file, web services etc View: Html page, what client sees Controller: CPU of the mechanism, gets request from web server, communicates with Model to get data, returns a view to the requestor. A url request is a function inside controller class
  • 14.
    Url Url nolonger points to the view/aspx page A Url maps to a controller class Allows more flexibility to map Urls Url routing engine, Route table Routes are tokenized strings Can use RegEx
  • 15.
    Controllers & ActionsResponds to requests Interacts with Model, and renders Views All controllers should have suffix “Controller” Derives from System.Web.MVC.Controller class  At the end, it is just a class, that has functions => Controller Actions that can’t be static, returns ActionResult
  • 16.
    ActionResult & ActionsController Actions return ActionResult ActionResult can be: ViewResult – Represents HTML and markup. EmptyResult – Represents no result. RedirectResult – Represents a redirection to a new URL. RedirectToRouteResult – Represents a redirection to a new controller action. JsonResult – Represents a JavaScript Object Notation result that can be used in an AJAX application. ContentResult – Represents a text result. Custom ActionResult
  • 17.
    Model, View, ControllerController: Gets the request from the requestor, (route mapping happens here), fires the action depending on the request ActionMethod: communicates with Model to get the data returns ActionResult ActionMethod can use ViewData, ViewData.Model or TempData to send data to View View generates the markup language for the requestor. View can use strongly typed Model
  • 18.
    Views Similar toexisting page No postback or view state Not all page events will fire Editing forms will be more work Separate page for viewing, editing, and updating Ajax will use UserControls as update panels but request still goes through the control
  • 19.
    Views View probablyshouldn’t directly access data sources or services. You should put the business logic inside the views; try to stay away from <%if … Use the ViewData which stores the model the view is rendering ViewPage<T>, ViewPage No postback
  • 20.
    DEMO Add anew controller Test, with model interaction
  • 21.
    How much backwardCompatibility is there? The MVC framework supports using the existing ASP.NET .ASPX, .ASCX, and .Master markup files as &quot;view templates&quot; (meaning you can easily use existing ASP.NET features like nested master pages, <%= %> snippets, declarative server controls, templates, data-binding, localization, etc).  It does not, however, use the existing post-back model for interactions back to the server.  Instead, you'll route all end-user interactions to a Controller class instead - which helps ensure clean separation of concerns and testability (it also means no viewstate or page lifecycle with MVC based views). The ASP.NET MVC framework fully supports existing ASP.NET features like forms/windows authentication, URL authorization, membership/roles, output and data caching, session/profile state management, health monitoring, configuration system, the provider architecture, etc.
  • 22.
    URL Routing URLRouting is mapping the incoming requests to controller’s action methods. There are handler’s settings in the web.config Routing table exists in Global.asax.cs Application_Start() registers the routing table You can use regex to define route mappings Route mapping works top to bottom, first match is called Download Phil Hack’s RouteDebug tool
  • 23.
    Route Examples <Controller>/<Action>/<Param>http://domain/ Home/CustomerDetail/45 Html.Link for creating outbound urls Html.Link(<Friendly Name>, <Action>, <Controller>)
  • 24.
    DEMO Add anew controller action , set the route
  • 25.
    Unit Testing MockObjects to simulate responses. Don’t have to go through a page or view Red/Green Testing Create instance of controller Uses Mock Objects You will need depedency injection down the road
  • 26.
    Future of ASP.NETMVC MVC for the Enterprise Classic Asp.Net for quicker implementations
  • 27.
    References Download theLatest MVC Beta from Codeplex Quick Start Guides http://quickstarts.asp.net/3-5-extensions/mvc/default.aspx
  • 28.
    Questions? ASP.NET MVCis a new paradigm for .NET Developers; a new way to think about programming web application. Any Questions / Comments … feel free to contact [email_address] Visit www.CodePlex.com/YABE