ASP.net MVC Overview -Divya Sharma
Agenda  What is MVC?  ASP .net MVC Request Execution  Controller in Detail  ASP .net Routing  Application Development and Code walkthrough  ASP .net Web forms v/s ASP .net MVC  Q&A
What is MVC?  MVC (Model-View-Controller) is an architectural pattern for web based applications.  The application is separated among Model, View and Controller which provides a loose coupling among business logic, UI logic and input logic.  ASP.net MVC framework provides an alternative to ASP.net web forms for building ASP.net web applications.
Features of MVC  Separation of application tasks viz. business logic, UI logic and input logic  Supports Test Driven Development (TDD)  Highly testable framework  Extensible and pluggable framework  Powerful URL-mapping component for comprehensible and searchable URLs  Supports existing ASP.net features viz. authentication, authorization, membership and roles, caching, state management, configuration, health monitoring etc.
Model  Model objects are the parts of the application that implement the logic for the application’s data domain. Often, model objects retrieve and store model state in a database.  For example, a Product object might retrieve information from a database, operate on it, and then write updated information back to a Products table in SQL Server.  In small applications, the model is often a conceptual separation instead of a physical one.
View  Views are the components that display the application’s user interface (UI). Typically, this UI is created from the model data.  An example would be an edit view of a Products table that displays text boxes, drop-down lists, and check boxes based on the current state of a Products object.
Controller  Controllers are the components that handle user interaction, work with the model, and ultimately select a view to render that displays UI. In an MVC application, the view only displays information; the controller handles and responds to user input and interaction.  For example, the controller handles query-string values, and passes these values to the model, which in turn queries the database by using the values.
MVC Request Execution RouteData MvcHandler Request object Object UrlRoutingModule MvcRouteHandler Controller (Http Module) Response Result Type Result Type object object The UrlRoutingModule and MvcRouteHandler classes are the entry points to the ASP.NET MVC framework. They perform the following actions:  Select the appropriate controller in an MVC Web application.  Obtain a specific controller instance.  Call the controller's Execute method.
Stages of Request Execution Stage Details first request for In the Global.asax file, Route objects are added to the RouteTable object. the application Perform routing The UrlRoutingModule module uses the first matching Route object in the RouteTable collection to create the RouteData object, which it then uses to create a RequestContext object. Create MVC The MvcRouteHandler object creates an instance of the MvcHandler class and passes request handler the RequestContext instance to the handler. Create The MvcHandler object uses the RequestContext instance to identify the controller IControllerFactory object (typically an instance of the DefaultControllerFactory class) to create the controller instance with. Execute The MvcHandler instance calls the controller's Execute method. controller Invoke action For controllers that inherit from the ControllerBase class, the ControllerActionInvoker object that is associated with the controller determines which action method of the controller class to call, and then calls that method. Execute result The action method receives user input, prepares the appropriate response data, and then executes the result by returning a result type. The built-in result types that can be executed include the following: ViewResult (which renders a view and is the most-often used result type), RedirectToRouteResult, RedirectResult, ContentResult, JsonResult, FileResult, and EmptyResult.
Controllers and ActionResult // action methods that render view pages // HelloWorld action method URL = Home/Index and Home/About with value for view data. URL = Home/HellowWorld [HandleError] public class public class HomeController : Controller HomeController : Controller { { public ActionResult Index() [ControllerAction] { public ActionResult ViewData["Msg"] = "Welcome" ; HelloWorld() return View(); { ViewData["Message"] = "Hello } World!"; public ActionResult About() return View(); { } return View(); } } }
Controllers and ActionResult // non action method // optional arguments for action method e.g. URL = Products/ShowProduct/P1?23 or [NonAction] URL = Products/ShowProduct/P1?23 private void DoSomething() public ActionResult ShowProduct(string { category, int? id) // Method logic. { } if(!id.HasValue) { // use Request object to retrieve query string value id = 0; public void Detail() } { // ... int id = } Convert.ToInt32(Request["id "]); }
ActionResult Type Action Result Helper Method Description ViewResult View Renders a view as a Web page. PartialViewResult PartialView Renders a partial view, which defines a section of a view that can be rendered inside another view. RedirectResult Redirect Redirects to another action method by using its URL. RedirectToRouteResult RedirectToAction Redirects to another action method. RedirectToRoute ContentResult Content Returns a user-defined content type. JsonResult Json Returns a serialized JSON object. JavaScriptResult JavaScript Returns a script that can be executed on the client. FileResult File Returns binary output to write to the response. EmptyResult (None) Represents a return value that is used if the action method must return a null result (void).
ASP .net Routing  The ASP.NET Routing module is responsible for mapping incoming browser requests to particular MVC controller actions.  Default URL format: controller/action/parameters  ASP.NET Routing is setup in two places in the application:  Web.config – uses 4 sections viz. system.web.httpModules, system.web.httpHandlers, system.webserver.modules, system.webserver.handlers  Global.asax.cs – Routes are provided and registered on Application_Start event.
Route Table in Global.asax.cs public class MvcApplication : System.Web.HttpApplication { 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 = "" } // Params ); } protected void Application_Start() { RegisterRoutes(RouteTable.Routes); } }
Setting Default Values of URL Parameters public static void RegisterRoutes(RouteCollection routes) { routes.MapPageRoute("", "Category/{action}/{categoryName}", "~/categoriespage.aspx", true, new RouteValueDictionary {{"categoryName", "food"}, {"action", "show"}}); } URL Parameter values /Category action = "show" (default value) categoryName = "food" (default value) /Category/add action = "add" categoryName = "food" (default value) /Category/add/beverages action = "add" categoryName= "beverages"
Adding Constraints to Routes public static void RegisterRoutes(RouteCollection routes) { routes.MapPageRoute("", "Category/{action}/{categoryName}", "~/categoriespage.aspx", true, new RouteValueDictionary {{"categoryName", "food"}, {"action", "show"}}, new RouteValueDictionary {{"locale", "[a-z]{2}-[a-z]{2}"},{"year", @"d{4}"}} ); } URL Result /US No match. Both locale and year are required. /US/08 No match. The constraint on year requires 4 digits. /US/2008 locale = "US" year = "2008"
Basic ASP .net MVC Application Development Prerequisites –  Microsoft Visual Studio 2008 Service Pack 1 or later  The ASP.NET MVC 2 framework (For Microsoft Visual Studio 2010 this framework comes in the package) Video : http://www.asp.net/mvc/videos/creating-a-movie-database-application-in-15-minutes-with-aspnet-mvc
ASP .net MVC Project Structure  There can be multiple views for a controller  Name of controller must have ‘Controller’ suffix  Name of page is not necessarily part of the URL  There can be multiple routes defined for an application and URL matching is done in order.
Code Walkthrough  http://weblogs.asp.net/scottgu/archive/2007/11
Advantages of MVC Based Web Application  Complex applications are easy to manage with divisions of Model, View and Controllers.  Provides strong routing mechanism with Front Controller pattern.  More control over application behavior with elimination of view state and server based forms  Better support for Test Driven Development (TDD)  Works well for development with large teams with multiple web developers and designers working simultaneously.
Advantages of Web Forms Based Web Application  Supports an event model that preserves state over HTTP, which benefits line-of-business Web application development.  Adds functionality to individual pages with Page Controller pattern.  Managing state information is easier with use of view state and server-based forms.  Less complex for application development with tightly integrated components.  Works well for small teams of web developers and designers who want to take advantage of the large number of components available for rapid application development.
ASP .net Web Forms v/s ASP .net MVC Feature ASP .net Web Forms ASP .net MVC Separation of concerns Less More Style of programming Event-driven Action result based Request execution Event based Controller based Complexity of state management Less More; does not support view state Control on application behavior Less More (Rendered HTML) Availability of controls In abundance + third party Less Support for server controls Yes No Support for ASP .net features like Yes Yes authentication, authorization, roles, configuration, etc. Support for TDD No Yes Ease of application development More Less Application maintainability Less More
When to Use ASP .net MVC?  ASP .net MVC is NOT a replacement of ASP .net web forms based applications.  The approach of application development must be decided based on the application requirements and features provided by ASP .net MVC to suite them.  Application development with ASP .net MVC is more complex as compared to web forms based applications with lack of readily available rich controls and less knowledge of the pattern in ASP .net web developers.  Application maintainability will be higher with separation of application tasks.
References  http://www.asp.net/mvc  http://msdn.microsoft.com/en-us/library/dd394709.aspx  http://weblogs.asp.net/scottgu/archive/2007/11/13/asp-net-mv  http://weblogs.asp.net/scottgu/archive/2007/12/03/asp-net-mv
Q&A
Thanks!

ASP .net MVC

  • 1.
  • 2.
    Agenda  What is MVC?  ASP .net MVC Request Execution  Controller in Detail  ASP .net Routing  Application Development and Code walkthrough  ASP .net Web forms v/s ASP .net MVC  Q&A
  • 3.
    What is MVC?  MVC (Model-View-Controller) is an architectural pattern for web based applications.  The application is separated among Model, View and Controller which provides a loose coupling among business logic, UI logic and input logic.  ASP.net MVC framework provides an alternative to ASP.net web forms for building ASP.net web applications.
  • 4.
    Features of MVC  Separation of application tasks viz. business logic, UI logic and input logic  Supports Test Driven Development (TDD)  Highly testable framework  Extensible and pluggable framework  Powerful URL-mapping component for comprehensible and searchable URLs  Supports existing ASP.net features viz. authentication, authorization, membership and roles, caching, state management, configuration, health monitoring etc.
  • 5.
    Model  Model objects are the parts of the application that implement the logic for the application’s data domain. Often, model objects retrieve and store model state in a database.  For example, a Product object might retrieve information from a database, operate on it, and then write updated information back to a Products table in SQL Server.  In small applications, the model is often a conceptual separation instead of a physical one.
  • 6.
    View  Views are the components that display the application’s user interface (UI). Typically, this UI is created from the model data.  An example would be an edit view of a Products table that displays text boxes, drop-down lists, and check boxes based on the current state of a Products object.
  • 7.
    Controller  Controllers are the components that handle user interaction, work with the model, and ultimately select a view to render that displays UI. In an MVC application, the view only displays information; the controller handles and responds to user input and interaction.  For example, the controller handles query-string values, and passes these values to the model, which in turn queries the database by using the values.
  • 8.
    MVC Request Execution RouteData MvcHandler Request object Object UrlRoutingModule MvcRouteHandler Controller (Http Module) Response Result Type Result Type object object The UrlRoutingModule and MvcRouteHandler classes are the entry points to the ASP.NET MVC framework. They perform the following actions:  Select the appropriate controller in an MVC Web application.  Obtain a specific controller instance.  Call the controller's Execute method.
  • 9.
    Stages of RequestExecution Stage Details first request for In the Global.asax file, Route objects are added to the RouteTable object. the application Perform routing The UrlRoutingModule module uses the first matching Route object in the RouteTable collection to create the RouteData object, which it then uses to create a RequestContext object. Create MVC The MvcRouteHandler object creates an instance of the MvcHandler class and passes request handler the RequestContext instance to the handler. Create The MvcHandler object uses the RequestContext instance to identify the controller IControllerFactory object (typically an instance of the DefaultControllerFactory class) to create the controller instance with. Execute The MvcHandler instance calls the controller's Execute method. controller Invoke action For controllers that inherit from the ControllerBase class, the ControllerActionInvoker object that is associated with the controller determines which action method of the controller class to call, and then calls that method. Execute result The action method receives user input, prepares the appropriate response data, and then executes the result by returning a result type. The built-in result types that can be executed include the following: ViewResult (which renders a view and is the most-often used result type), RedirectToRouteResult, RedirectResult, ContentResult, JsonResult, FileResult, and EmptyResult.
  • 10.
    Controllers and ActionResult //action methods that render view pages // HelloWorld action method URL = Home/Index and Home/About with value for view data. URL = Home/HellowWorld [HandleError] public class public class HomeController : Controller HomeController : Controller { { public ActionResult Index() [ControllerAction] { public ActionResult ViewData["Msg"] = "Welcome" ; HelloWorld() return View(); { ViewData["Message"] = "Hello } World!"; public ActionResult About() return View(); { } return View(); } } }
  • 11.
    Controllers and ActionResult //non action method // optional arguments for action method e.g. URL = Products/ShowProduct/P1?23 or [NonAction] URL = Products/ShowProduct/P1?23 private void DoSomething() public ActionResult ShowProduct(string { category, int? id) // Method logic. { } if(!id.HasValue) { // use Request object to retrieve query string value id = 0; public void Detail() } { // ... int id = } Convert.ToInt32(Request["id "]); }
  • 12.
    ActionResult Type Action Result Helper Method Description ViewResult View Renders a view as a Web page. PartialViewResult PartialView Renders a partial view, which defines a section of a view that can be rendered inside another view. RedirectResult Redirect Redirects to another action method by using its URL. RedirectToRouteResult RedirectToAction Redirects to another action method. RedirectToRoute ContentResult Content Returns a user-defined content type. JsonResult Json Returns a serialized JSON object. JavaScriptResult JavaScript Returns a script that can be executed on the client. FileResult File Returns binary output to write to the response. EmptyResult (None) Represents a return value that is used if the action method must return a null result (void).
  • 13.
    ASP .net Routing  The ASP.NET Routing module is responsible for mapping incoming browser requests to particular MVC controller actions.  Default URL format: controller/action/parameters  ASP.NET Routing is setup in two places in the application:  Web.config – uses 4 sections viz. system.web.httpModules, system.web.httpHandlers, system.webserver.modules, system.webserver.handlers  Global.asax.cs – Routes are provided and registered on Application_Start event.
  • 14.
    Route Table inGlobal.asax.cs public class MvcApplication : System.Web.HttpApplication { 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 = "" } // Params ); } protected void Application_Start() { RegisterRoutes(RouteTable.Routes); } }
  • 15.
    Setting Default Valuesof URL Parameters public static void RegisterRoutes(RouteCollection routes) { routes.MapPageRoute("", "Category/{action}/{categoryName}", "~/categoriespage.aspx", true, new RouteValueDictionary {{"categoryName", "food"}, {"action", "show"}}); } URL Parameter values /Category action = "show" (default value) categoryName = "food" (default value) /Category/add action = "add" categoryName = "food" (default value) /Category/add/beverages action = "add" categoryName= "beverages"
  • 16.
    Adding Constraints toRoutes public static void RegisterRoutes(RouteCollection routes) { routes.MapPageRoute("", "Category/{action}/{categoryName}", "~/categoriespage.aspx", true, new RouteValueDictionary {{"categoryName", "food"}, {"action", "show"}}, new RouteValueDictionary {{"locale", "[a-z]{2}-[a-z]{2}"},{"year", @"d{4}"}} ); } URL Result /US No match. Both locale and year are required. /US/08 No match. The constraint on year requires 4 digits. /US/2008 locale = "US" year = "2008"
  • 17.
    Basic ASP .netMVC Application Development Prerequisites –  Microsoft Visual Studio 2008 Service Pack 1 or later  The ASP.NET MVC 2 framework (For Microsoft Visual Studio 2010 this framework comes in the package) Video : http://www.asp.net/mvc/videos/creating-a-movie-database-application-in-15-minutes-with-aspnet-mvc
  • 18.
    ASP .net MVCProject Structure  There can be multiple views for a controller  Name of controller must have ‘Controller’ suffix  Name of page is not necessarily part of the URL  There can be multiple routes defined for an application and URL matching is done in order.
  • 19.
    Code Walkthrough  http://weblogs.asp.net/scottgu/archive/2007/11
  • 20.
    Advantages of MVCBased Web Application  Complex applications are easy to manage with divisions of Model, View and Controllers.  Provides strong routing mechanism with Front Controller pattern.  More control over application behavior with elimination of view state and server based forms  Better support for Test Driven Development (TDD)  Works well for development with large teams with multiple web developers and designers working simultaneously.
  • 21.
    Advantages of WebForms Based Web Application  Supports an event model that preserves state over HTTP, which benefits line-of-business Web application development.  Adds functionality to individual pages with Page Controller pattern.  Managing state information is easier with use of view state and server-based forms.  Less complex for application development with tightly integrated components.  Works well for small teams of web developers and designers who want to take advantage of the large number of components available for rapid application development.
  • 22.
    ASP .net WebForms v/s ASP .net MVC Feature ASP .net Web Forms ASP .net MVC Separation of concerns Less More Style of programming Event-driven Action result based Request execution Event based Controller based Complexity of state management Less More; does not support view state Control on application behavior Less More (Rendered HTML) Availability of controls In abundance + third party Less Support for server controls Yes No Support for ASP .net features like Yes Yes authentication, authorization, roles, configuration, etc. Support for TDD No Yes Ease of application development More Less Application maintainability Less More
  • 23.
    When to UseASP .net MVC?  ASP .net MVC is NOT a replacement of ASP .net web forms based applications.  The approach of application development must be decided based on the application requirements and features provided by ASP .net MVC to suite them.  Application development with ASP .net MVC is more complex as compared to web forms based applications with lack of readily available rich controls and less knowledge of the pattern in ASP .net web developers.  Application maintainability will be higher with separation of application tasks.
  • 24.
    References  http://www.asp.net/mvc  http://msdn.microsoft.com/en-us/library/dd394709.aspx  http://weblogs.asp.net/scottgu/archive/2007/11/13/asp-net-mv  http://weblogs.asp.net/scottgu/archive/2007/12/03/asp-net-mv
  • 25.
  • 26.

Editor's Notes

  • #9 Requests to an ASP.NET MVC-based Web application first pass through the UrlRoutingModule object, which is an HTTP module. This module parses the request and performs route selection. The UrlRoutingModule object selects the first route object that matches the current request. (A route object is a class that implements RouteBase , and is typically an instance of the Route class.) If no routes match, the UrlRoutingModule object does nothing and lets the request fall back to the regular ASP.NET or IIS request processing. From the selected Route object, the UrlRoutingModule object obtains an object that implements the IRouteHandler interface and that is associated with the Route object. Typically, in an MVC application, this will be an instance of the MvcRouteHandler class. The MvcRouteHandler instance creates an MvcHandler object that implements the IHttpHandler interface. The MvcHandler object then selects the controller that will ultimately handle the request.