ASP.NET MVC Introduction to ASP.NET MVC and Example Walkthrough
Rajat Arya (rajata@U) eFECS - OIM
Agenda 2
Definition what is ASP.NET MVC? Functional Description how does ASP.NET MVC actually work? Goal / Benefits why is it important? ASP.NET MVC Implementation Walkthrough lets see this thing actually working Questions? Reference Materials
4/21/2009 - Rajat Arya (rajata@u) - DAWG
ASP.NET MVC Definition 3
The ASP.NET MVC framework provides an alternative to the ASP.NET Web Forms pattern for creating MVC-based Web applications. The ASP.NET MVC framework is a lightweight, highly testable presentation framework that is integrated with existing ASP.NET features, such as master pages and membership-based authentication. The MVC framework is defined in the System.Web.Mvc namespace and is a fundamental, supported part of the System.Web namespace. (taken from http://www.asp.net/learn/mvc/tutorial-01-cs.aspx) 4/21/2009 - Rajat Arya (rajata@u) - DAWG
Functional Description (is a) 4
Set of classes, containing: Base class for Controllers Base class for Views (extend ASP.NET View class) Base class for Responses (ActionResult) Default classes for Routing (wiring URLs to Controllers) Plugin for Visual Studio Adds project template
4/21/2009 - Rajat Arya (rajata@u) - DAWG
Functional Description (how it works) 5
Registers itself with ASP.NET in Default.aspx.cs as an
HttpHandler and then handles all HTTP requests
public partial class _Default : Page { public void Page_Load(object sender, System.EventArgs e) { HttpContext.Current.RewritePath(Request.ApplicationPath, false); IHttpHandler httpHandler = new MvcHttpHandler(); httpHandler.ProcessRequest(HttpContext.Current); } }
Enables Routing System through web.config changes 4/21/2009 - Rajat Arya (rajata@u) - DAWG
Functional Description (the parts) 6
Views Display the application's user interface (UI). Typically, this UI is created from the model data Ex. 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. Controllers Handle user interaction, work with the model, and ultimately select a view to render that displays UI. Handles and responds to user input and interaction Ex. handles query-string values, and passes these values to the model, which in turn queries the database by using the values. Routing Define rules to route URLs to specific Controllers. Providing inputs to specific Actions defined by the Controller. Ex. http://www.example.com/products/info/1 could be routed to ActionResult ProductsController.Information(int id) method
(parts taken from http://www.asp.net/learn/mvc/tutorial-01-cs.aspx) 4/21/2009 - Rajat Arya (rajata@u) - DAWG
Functional Description (Views) 7
A view is a standard (X)HTML document that can
contain scripts. Can be defined as an .aspx page, but no codebehind Example: \Views\Home\Index.aspx <%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>
Index The current date and time is <% Response.Write(DateTime.Now);%>
4/21/2009 - Rajat Arya (rajata@u) - DAWG
Functional Description (Controllers) 8
Class that extends System.Web.Mvc.Controller class Defines public methods that return ActionResult for Actions the
controller handles Each ActionResult method accepts inputs, does the processing (works with Model / Repository / Business Logic Layer) and returns ActionResult to user A View is returned as a ViewResult from the Controller Example: ProductsController public class ProductsController : Controller { // GET: /Products/ public ActionResult Index() { // Add action logic here return View(); } } 4/21/2009 - Rajat Arya (rajata@u) - DAWG
Functional Description (Routing) 9
Responsible for mapping browser requests to a particular MVC
Controller action. Enabled in web.config file Route table created in Global.asax file, called in Application_Start() method public static void RegisterRoutes(RouteCollection routes) { routes.MapRoute( "Default", // Unique route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = "" } // defaults ); routes.MapRoute( "ProductInfo", "Products/Info/{id}", new { controller = "Products", action = "Info", id = "" } // defaults ); } 4/21/2009 - Rajat Arya (rajata@u) - DAWG
Functional Description (Passing Data) 10
ViewData object is used to pass data between
Controllers and Views ViewData is a dictionary object, which has a Model property on it of type object
Use dictionary to pass data back, or use model object to set a model that the View is to display
Controller does the following: return View(“ViewName”, model); ViewData[“id”] = 23; return View();
4/21/2009 - Rajat Arya (rajata@u) - DAWG
Functional Definition (request to response) 11
1. URL request for /products/info/1 2. Default.aspx.cs invokes MvcHttpHandler to handle request 3. MvcHttpHandler refers to Routing Rules registered in Global.asax.cs (in Application_Start) to find a Controller/Action that matches request (/products/info/{id}) 4. MvcHttpHandler instantiates controller and invokes corresponding action method (using built in object mapper to map parameters on URL as inputs to action method) 5. Calls ProductsController.Info(id=1) code 6. Info method works with Business Logic objects to perform operation, sets any ViewData and returns a View as an ActionResult
4/21/2009 - Rajat Arya (rajata@u) - DAWG
Goals / Benefits (1) 12
Separation of Concerns
Separation of application tasks (input logic, business logic, and UI logic) Does not use view state or server-based forms.
Testability
All core contracts in the MVC framework are interface-based and can be tested by using mock objects, which are simulated objects that imitate the behavior of actual objects in the application You can unit-test the application without having to run the controllers in an ASP.NET process, which makes unit testing fast and flexible. You can use any unit-testing framework that is compatible with the .NET Framework.
Extensibility
All core contracts in the MVC framework are interface-based Supports the use of Dependency Injection (DI) and Inversion of Control (IOC) container models. Plug in your own view engine, URL routing policy, action-method parameter serialization, and other components.
Compatibility
ASP.NET MVC lets you use features such as forms authentication and Windows authentication, URL authorization, membership and roles, output and data caching, session and profile state management, health monitoring, the configuration system, and the provider architecture. You can use existing ASP.NET features with the ASP.NET MVC framework, such as nested master pages, in-line expressions (<%= %>), declarative server controls, templates, data-binding, localization, and so on.
4/21/2009 - Rajat Arya (rajata@u) - DAWG
(parts taken from http://www.asp.net/learn/mvc/tutorial-01-cs.aspx)
Goals / Benefits (2) 13
Powerful URL Mapping Component
Uses a Front Controller pattern that processes Web application requests through a single controller. This enables you to design an application that supports a rich routing infrastructure. For more information, see Front Controller on the MSDN Web site. URLs do not have to include file-name extensions, and are designed to support URL naming patterns that work well for search engine optimization (SEO) and representational state transfer (REST) addressing.
Well Documented and Lots of Active Development Fully Supported by Microsoft Open-Source under MS-PL license Free!
4/21/2009 - Rajat Arya (rajata@u) - DAWG
(parts taken from http://www.asp.net/learn/mvc/tutorial-01-cs.aspx)
ASP.NET MVC Implementation Walkthrough 14
Small sample ASP.NET MVC application. Taken from asp.net/mvc website (http://static.asp.net/asp.net/images/mvc/32/CS/Cont actManager_7_CS.zip)
4/21/2009 - Rajat Arya (rajata@u) - DAWG
Fin. Questions?
Reference Materials 16
http://www.asp.net/learn/mvc/ - really well done –
go here first! http://weblogs.asp.net/scottgu/archive/tags/MVC/ASP. - Scott Guthrie’s posts, goodness, code, http://www.hanselman.com/blog/CategoryView.aspx?ca – Scott Hanselman’s posts, good, less code Unity/IoC Running on IIS6 (or here)
4/21/2009 - Rajat Arya (rajata@u) - DAWG