SlideShare une entreprise Scribd logo
1  sur  26
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!

Contenu connexe

Tendances

MVC Architecture in ASP.Net By Nyros Developer
MVC Architecture in ASP.Net By Nyros DeveloperMVC Architecture in ASP.Net By Nyros Developer
MVC Architecture in ASP.Net By Nyros DeveloperNyros Technologies
 
MVC Architecture
MVC ArchitectureMVC Architecture
MVC ArchitecturePrem Sanil
 
Ppt of Basic MVC Structure
Ppt of Basic MVC StructurePpt of Basic MVC Structure
Ppt of Basic MVC StructureDipika Wadhvani
 
ASP.NET Tutorial - Presentation 1
ASP.NET Tutorial - Presentation 1ASP.NET Tutorial - Presentation 1
ASP.NET Tutorial - Presentation 1Kumar S
 
Introduction to Swagger
Introduction to SwaggerIntroduction to Swagger
Introduction to SwaggerKnoldus Inc.
 
Asp.Net Core MVC with Entity Framework
Asp.Net Core MVC with Entity FrameworkAsp.Net Core MVC with Entity Framework
Asp.Net Core MVC with Entity FrameworkShravan A
 
What is REST API? REST API Concepts and Examples | Edureka
What is REST API? REST API Concepts and Examples | EdurekaWhat is REST API? REST API Concepts and Examples | Edureka
What is REST API? REST API Concepts and Examples | EdurekaEdureka!
 
MVVM ( Model View ViewModel )
MVVM ( Model View ViewModel )MVVM ( Model View ViewModel )
MVVM ( Model View ViewModel )Ahmed Emad
 
Introduction to ASP.NET MVC
Introduction to ASP.NET MVCIntroduction to ASP.NET MVC
Introduction to ASP.NET MVCKhaled Musaied
 
ASP.NET Web API
ASP.NET Web APIASP.NET Web API
ASP.NET Web APIhabib_786
 
Introduction to Struts 1.3
Introduction to Struts 1.3Introduction to Struts 1.3
Introduction to Struts 1.3Ilio Catallo
 
Design Pattern - MVC, MVP and MVVM
Design Pattern - MVC, MVP and MVVMDesign Pattern - MVC, MVP and MVVM
Design Pattern - MVC, MVP and MVVMMudasir Qazi
 
ASP.NET Web API and HTTP Fundamentals
ASP.NET Web API and HTTP FundamentalsASP.NET Web API and HTTP Fundamentals
ASP.NET Web API and HTTP FundamentalsIdo Flatow
 

Tendances (20)

Model View Controller (MVC)
Model View Controller (MVC)Model View Controller (MVC)
Model View Controller (MVC)
 
MVC Architecture in ASP.Net By Nyros Developer
MVC Architecture in ASP.Net By Nyros DeveloperMVC Architecture in ASP.Net By Nyros Developer
MVC Architecture in ASP.Net By Nyros Developer
 
MVC Architecture
MVC ArchitectureMVC Architecture
MVC Architecture
 
Ppt of Basic MVC Structure
Ppt of Basic MVC StructurePpt of Basic MVC Structure
Ppt of Basic MVC Structure
 
Spring MVC Framework
Spring MVC FrameworkSpring MVC Framework
Spring MVC Framework
 
An Introduction To REST API
An Introduction To REST APIAn Introduction To REST API
An Introduction To REST API
 
ASP.NET Tutorial - Presentation 1
ASP.NET Tutorial - Presentation 1ASP.NET Tutorial - Presentation 1
ASP.NET Tutorial - Presentation 1
 
Introduction to Swagger
Introduction to SwaggerIntroduction to Swagger
Introduction to Swagger
 
Asp.Net Core MVC with Entity Framework
Asp.Net Core MVC with Entity FrameworkAsp.Net Core MVC with Entity Framework
Asp.Net Core MVC with Entity Framework
 
What is REST API? REST API Concepts and Examples | Edureka
What is REST API? REST API Concepts and Examples | EdurekaWhat is REST API? REST API Concepts and Examples | Edureka
What is REST API? REST API Concepts and Examples | Edureka
 
Why MVC?
Why MVC?Why MVC?
Why MVC?
 
Spring MVC
Spring MVCSpring MVC
Spring MVC
 
MVVM ( Model View ViewModel )
MVVM ( Model View ViewModel )MVVM ( Model View ViewModel )
MVVM ( Model View ViewModel )
 
Web api
Web apiWeb api
Web api
 
Introduction to ASP.NET MVC
Introduction to ASP.NET MVCIntroduction to ASP.NET MVC
Introduction to ASP.NET MVC
 
Android MVVM
Android MVVMAndroid MVVM
Android MVVM
 
ASP.NET Web API
ASP.NET Web APIASP.NET Web API
ASP.NET Web API
 
Introduction to Struts 1.3
Introduction to Struts 1.3Introduction to Struts 1.3
Introduction to Struts 1.3
 
Design Pattern - MVC, MVP and MVVM
Design Pattern - MVC, MVP and MVVMDesign Pattern - MVC, MVP and MVVM
Design Pattern - MVC, MVP and MVVM
 
ASP.NET Web API and HTTP Fundamentals
ASP.NET Web API and HTTP FundamentalsASP.NET Web API and HTTP Fundamentals
ASP.NET Web API and HTTP Fundamentals
 

En vedette

Physical architecture of sql server
Physical architecture of sql serverPhysical architecture of sql server
Physical architecture of sql serverDivya Sharma
 
Microsoft SQL Server internals & architecture
Microsoft SQL Server internals & architectureMicrosoft SQL Server internals & architecture
Microsoft SQL Server internals & architectureKevin Kline
 
Ms sql server architecture
Ms sql server architectureMs sql server architecture
Ms sql server architectureAjeet Singh
 
Microsoft sql server architecture
Microsoft sql server architectureMicrosoft sql server architecture
Microsoft sql server architectureNaveen Boda
 
MS Sql Server: Introduction To Database Concepts
MS Sql Server: Introduction To Database ConceptsMS Sql Server: Introduction To Database Concepts
MS Sql Server: Introduction To Database ConceptsDataminingTools Inc
 
What's new in asp.net mvc 4
What's new in asp.net mvc 4What's new in asp.net mvc 4
What's new in asp.net mvc 4Simone Chiaretta
 
Asp.net routing with mvc deep dive
Asp.net routing with mvc deep diveAsp.net routing with mvc deep dive
Asp.net routing with mvc deep diveStacy Vicknair
 
Nikhil Khandelwal BCA 3rd Year
Nikhil Khandelwal BCA 3rd YearNikhil Khandelwal BCA 3rd Year
Nikhil Khandelwal BCA 3rd Yeardezyneecole
 
Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app...
Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app...Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app...
Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app...Dan Wahlin
 
Asp.Net MVC - Razor Syntax
Asp.Net MVC - Razor SyntaxAsp.Net MVC - Razor Syntax
Asp.Net MVC - Razor SyntaxRenier Serven
 
Bca sem 5 c# practical
Bca sem 5 c# practicalBca sem 5 c# practical
Bca sem 5 c# practicalHitesh Patel
 
ASP.NET MVC Workshop for Women in Technology
ASP.NET MVC Workshop for Women in TechnologyASP.NET MVC Workshop for Women in Technology
ASP.NET MVC Workshop for Women in TechnologyMałgorzata Borzęcka
 
Sms pro - bulk SMS sending software
Sms pro - bulk SMS sending softwareSms pro - bulk SMS sending software
Sms pro - bulk SMS sending softwareLive Tecnologies
 

En vedette (20)

Physical architecture of sql server
Physical architecture of sql serverPhysical architecture of sql server
Physical architecture of sql server
 
MS-SQL SERVER ARCHITECTURE
MS-SQL SERVER ARCHITECTUREMS-SQL SERVER ARCHITECTURE
MS-SQL SERVER ARCHITECTURE
 
Microsoft SQL Server internals & architecture
Microsoft SQL Server internals & architectureMicrosoft SQL Server internals & architecture
Microsoft SQL Server internals & architecture
 
Ms sql server architecture
Ms sql server architectureMs sql server architecture
Ms sql server architecture
 
Microsoft sql server architecture
Microsoft sql server architectureMicrosoft sql server architecture
Microsoft sql server architecture
 
Sql Server Basics
Sql Server BasicsSql Server Basics
Sql Server Basics
 
MS Sql Server: Introduction To Database Concepts
MS Sql Server: Introduction To Database ConceptsMS Sql Server: Introduction To Database Concepts
MS Sql Server: Introduction To Database Concepts
 
What's new in asp.net mvc 4
What's new in asp.net mvc 4What's new in asp.net mvc 4
What's new in asp.net mvc 4
 
Asp.net routing with mvc deep dive
Asp.net routing with mvc deep diveAsp.net routing with mvc deep dive
Asp.net routing with mvc deep dive
 
Nikhil Khandelwal BCA 3rd Year
Nikhil Khandelwal BCA 3rd YearNikhil Khandelwal BCA 3rd Year
Nikhil Khandelwal BCA 3rd Year
 
Validation controls in asp
Validation controls in aspValidation controls in asp
Validation controls in asp
 
Licenças para área de restinga
Licenças para área de restingaLicenças para área de restinga
Licenças para área de restinga
 
Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app...
Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app...Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app...
Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app...
 
Asp.Net MVC - Razor Syntax
Asp.Net MVC - Razor SyntaxAsp.Net MVC - Razor Syntax
Asp.Net MVC - Razor Syntax
 
Bca sem 5 c# practical
Bca sem 5 c# practicalBca sem 5 c# practical
Bca sem 5 c# practical
 
ASP.NET MVC Workshop for Women in Technology
ASP.NET MVC Workshop for Women in TechnologyASP.NET MVC Workshop for Women in Technology
ASP.NET MVC Workshop for Women in Technology
 
Sms pro - bulk SMS sending software
Sms pro - bulk SMS sending softwareSms pro - bulk SMS sending software
Sms pro - bulk SMS sending software
 
Web Config
Web ConfigWeb Config
Web Config
 
Práctica para writer
Práctica para writerPráctica para writer
Práctica para writer
 
Story planner
Story plannerStory planner
Story planner
 

Similaire à ASP.net MVC Framework Overview

Controllers & actions
Controllers & actionsControllers & actions
Controllers & actionsEyal Vardi
 
Murach: How to transfer data from controllers
Murach: How to transfer data from controllersMurach: How to transfer data from controllers
Murach: How to transfer data from controllersMahmoudOHassouna
 
Developing ASP.NET Applications Using the Model View Controller Pattern
Developing ASP.NET Applications Using the Model View Controller PatternDeveloping ASP.NET Applications Using the Model View Controller Pattern
Developing ASP.NET Applications Using the Model View Controller Patterngoodfriday
 
ASP.NET MVC Controllers & Actions
ASP.NET MVC Controllers & ActionsASP.NET MVC Controllers & Actions
ASP.NET MVC Controllers & Actionsonsela
 
Asp.Net Mvc
Asp.Net MvcAsp.Net Mvc
Asp.Net Mvcmicham
 
Mvc interview questions – deep dive jinal desai
Mvc interview questions – deep dive   jinal desaiMvc interview questions – deep dive   jinal desai
Mvc interview questions – deep dive jinal desaijinaldesailive
 
Asp.Net MVC Framework Design Pattern
Asp.Net MVC Framework Design PatternAsp.Net MVC Framework Design Pattern
Asp.Net MVC Framework Design Patternmaddinapudi
 
Simple mvc4 prepared by gigin krishnan
Simple mvc4 prepared by gigin krishnanSimple mvc4 prepared by gigin krishnan
Simple mvc4 prepared by gigin krishnanGigin Krishnan
 
Using a model view-view model architecture for iOS apps
Using a model view-view model architecture for iOS appsUsing a model view-view model architecture for iOS apps
Using a model view-view model architecture for iOS appsallanh0526
 
Sitecore MVC (London User Group, April 29th 2014)
Sitecore MVC (London User Group, April 29th 2014)Sitecore MVC (London User Group, April 29th 2014)
Sitecore MVC (London User Group, April 29th 2014)Ruud van Falier
 
ASP.NET - Building Web Application..in the right way!
ASP.NET - Building Web Application..in the right way!ASP.NET - Building Web Application..in the right way!
ASP.NET - Building Web Application..in the right way!Fioriela Bego
 
ASP.NET - Building Web Application..in the right way!
ASP.NET - Building Web Application..in the right way!ASP.NET - Building Web Application..in the right way!
ASP.NET - Building Web Application..in the right way!Commit Software Sh.p.k.
 
ASP.NET MVC Internals
ASP.NET MVC InternalsASP.NET MVC Internals
ASP.NET MVC InternalsVitaly Baum
 
Building Modern Websites with ASP.NET by Rachel Appel
Building Modern Websites with ASP.NET by Rachel AppelBuilding Modern Websites with ASP.NET by Rachel Appel
Building Modern Websites with ASP.NET by Rachel Appel.NET Conf UY
 
ASP.NET Internals
ASP.NET InternalsASP.NET Internals
ASP.NET InternalsGoSharp
 

Similaire à ASP.net MVC Framework Overview (20)

Controllers & actions
Controllers & actionsControllers & actions
Controllers & actions
 
Murach: How to transfer data from controllers
Murach: How to transfer data from controllersMurach: How to transfer data from controllers
Murach: How to transfer data from controllers
 
Developing ASP.NET Applications Using the Model View Controller Pattern
Developing ASP.NET Applications Using the Model View Controller PatternDeveloping ASP.NET Applications Using the Model View Controller Pattern
Developing ASP.NET Applications Using the Model View Controller Pattern
 
ASP.NET MVC Controllers & Actions
ASP.NET MVC Controllers & ActionsASP.NET MVC Controllers & Actions
ASP.NET MVC Controllers & Actions
 
Asp.Net Mvc
Asp.Net MvcAsp.Net Mvc
Asp.Net Mvc
 
Mvc interview questions – deep dive jinal desai
Mvc interview questions – deep dive   jinal desaiMvc interview questions – deep dive   jinal desai
Mvc interview questions – deep dive jinal desai
 
Asp.Net MVC Framework Design Pattern
Asp.Net MVC Framework Design PatternAsp.Net MVC Framework Design Pattern
Asp.Net MVC Framework Design Pattern
 
Simple mvc4 prepared by gigin krishnan
Simple mvc4 prepared by gigin krishnanSimple mvc4 prepared by gigin krishnan
Simple mvc4 prepared by gigin krishnan
 
Spring Web MVC
Spring Web MVCSpring Web MVC
Spring Web MVC
 
Chapter4.pptx
Chapter4.pptxChapter4.pptx
Chapter4.pptx
 
Asp.net mvc
Asp.net mvcAsp.net mvc
Asp.net mvc
 
Using a model view-view model architecture for iOS apps
Using a model view-view model architecture for iOS appsUsing a model view-view model architecture for iOS apps
Using a model view-view model architecture for iOS apps
 
Sitecore MVC (London User Group, April 29th 2014)
Sitecore MVC (London User Group, April 29th 2014)Sitecore MVC (London User Group, April 29th 2014)
Sitecore MVC (London User Group, April 29th 2014)
 
ASP.NET - Building Web Application..in the right way!
ASP.NET - Building Web Application..in the right way!ASP.NET - Building Web Application..in the right way!
ASP.NET - Building Web Application..in the right way!
 
ASP.NET - Building Web Application..in the right way!
ASP.NET - Building Web Application..in the right way!ASP.NET - Building Web Application..in the right way!
ASP.NET - Building Web Application..in the right way!
 
ASP.NET MVC Internals
ASP.NET MVC InternalsASP.NET MVC Internals
ASP.NET MVC Internals
 
Sessi
SessiSessi
Sessi
 
Building Modern Websites with ASP.NET by Rachel Appel
Building Modern Websites with ASP.NET by Rachel AppelBuilding Modern Websites with ASP.NET by Rachel Appel
Building Modern Websites with ASP.NET by Rachel Appel
 
ASP.NET Internals
ASP.NET InternalsASP.NET Internals
ASP.NET Internals
 
Day7
Day7Day7
Day7
 

Dernier

How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 

Dernier (20)

How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 

ASP.net MVC Framework Overview

  • 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 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.
  • 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 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); } }
  • 15. 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"
  • 16. 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"
  • 17. 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
  • 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. Code Walkthrough  http://weblogs.asp.net/scottgu/archive/2007/11
  • 20. 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.
  • 21. 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.
  • 22. 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
  • 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. 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. Q&A

Notes de l'éditeur

  1. 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.