ASP .net MVC


Published on

Introduction to ASP .net MVC

Published in: Technology
  • Be the first to comment

ASP .net MVC

  1. 1. MVCOverview-Divya Sharma
  2. 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. 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.  MVC framework provides an alternative to web forms for building web applications.
  4. 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 features viz. authentication, authorization, membership and roles, caching, state management, configuration, health monitoring etc.
  5. 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. 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. 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. 8. MVC Request Execution RouteData MvcHandler Request object Object UrlRoutingModule MvcRouteHandler Controller (Http Module) Response Result Type Result Type object objectThe 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 controllers Execute method.
  9. 9. Stages of Request ExecutionStage Detailsfirst request for In the Global.asax file, Route objects are added to the RouteTable object.the applicationPerform 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 passesrequest handler the RequestContext instance to the handler.Create The MvcHandler object uses the RequestContext instance to identify thecontroller IControllerFactory object (typically an instance of the DefaultControllerFactory class) to create the controller instance with.Execute The MvcHandler instance calls the controllers Execute method.controllerInvoke 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. 10. Controllers and ActionResult// action methods that render view pages // HelloWorld action methodURL = Home/Index and Home/About with value for view data. URL = Home/HellowWorld[HandleError] public classpublic 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. 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?23private void DoSomething() public ActionResult ShowProduct(string{ category, int? id) // Method logic. {} if(!id.HasValue) {// use Request object toretrieve query string value id = 0;public void Detail() }{ // ... int id = }Convert.ToInt32(Request["id"]);}
  12. 12. ActionResult TypeAction Result Helper Method DescriptionViewResult 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. RedirectToRouteContentResult 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. 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. 14. Route Table in Global.asax.cspublic 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. 15. Setting Default Values ofURL Parameterspublic 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. 16. Adding Constraints to Routespublic static void RegisterRoutes(RouteCollection routes){ routes.MapPageRoute("", "Category/{action}/{categoryName}","~/categoriespage.aspx", true, new RouteValueDictionary{{"categoryName", "food"}, {"action", "show"}}, newRouteValueDictionary {{"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. 17. Basic ASP .net MVCApplication DevelopmentPrerequisites – 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 :
  18. 18. 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.
  19. 19. Code Walkthrough
  20. 20. Advantages of MVC BasedWeb 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. 21. Advantages of Web Forms BasedWeb 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. 22. ASP .net Web Forms v/s ASP .net MVCFeature ASP .net Web Forms ASP .net MVCSeparation of concerns Less MoreStyle of programming Event-driven Action result basedRequest execution Event based Controller basedComplexity of state management Less More; does not support view stateControl on application behavior Less More(Rendered HTML)Availability of controls In abundance + third party LessSupport for server controls Yes NoSupport for ASP .net features like Yes Yesauthentication, authorization, roles,configuration, etc.Support for TDD No YesEase of application development More LessApplication maintainability Less More
  23. 23. 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.
  24. 24. References
  25. 25. Q&A
  26. 26. Thanks!