SlideShare ist ein Scribd-Unternehmen logo
1 von 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!

Weitere ähnliche Inhalte

Was ist angesagt?

MVC ppt presentation
MVC ppt presentationMVC ppt presentation
MVC ppt presentationBhavin Shah
 
ASP.NET MVC Presentation
ASP.NET MVC PresentationASP.NET MVC Presentation
ASP.NET MVC Presentationivpol
 
Intro to vue.js
Intro to vue.jsIntro to vue.js
Intro to vue.jsTechMagic
 
Getting started with Redux js
Getting started with Redux jsGetting started with Redux js
Getting started with Redux jsCitrix
 
ASP.NET - Life cycle of asp
ASP.NET - Life cycle of aspASP.NET - Life cycle of asp
ASP.NET - Life cycle of asppriya Nithya
 
Introduction to React JS for beginners
Introduction to React JS for beginners Introduction to React JS for beginners
Introduction to React JS for beginners Varun Raj
 
ASP.NET Tutorial - Presentation 1
ASP.NET Tutorial - Presentation 1ASP.NET Tutorial - Presentation 1
ASP.NET Tutorial - Presentation 1Kumar S
 
VueJS Introduction
VueJS IntroductionVueJS Introduction
VueJS IntroductionDavid Ličen
 
introduction to Vue.js 3
introduction to Vue.js 3 introduction to Vue.js 3
introduction to Vue.js 3 ArezooKmn
 
ASP.NET Core MVC + Web API with Overview
ASP.NET Core MVC + Web API with OverviewASP.NET Core MVC + Web API with Overview
ASP.NET Core MVC + Web API with OverviewShahed Chowdhuri
 
The Point of Vue - Intro to Vue.js
The Point of Vue - Intro to Vue.jsThe Point of Vue - Intro to Vue.js
The Point of Vue - Intro to Vue.jsHolly Schinsky
 
Deep dive into Vue.js
Deep dive into Vue.jsDeep dive into Vue.js
Deep dive into Vue.js선협 이
 

Was ist angesagt? (20)

VueJS: The Simple Revolution
VueJS: The Simple RevolutionVueJS: The Simple Revolution
VueJS: The Simple Revolution
 
MVC ppt presentation
MVC ppt presentationMVC ppt presentation
MVC ppt presentation
 
ASP.NET MVC Presentation
ASP.NET MVC PresentationASP.NET MVC Presentation
ASP.NET MVC Presentation
 
Vue.js
Vue.jsVue.js
Vue.js
 
An introduction to Vue.js
An introduction to Vue.jsAn introduction to Vue.js
An introduction to Vue.js
 
Intro to vue.js
Intro to vue.jsIntro to vue.js
Intro to vue.js
 
Vue js for beginner
Vue js for beginner Vue js for beginner
Vue js for beginner
 
Getting started with Redux js
Getting started with Redux jsGetting started with Redux js
Getting started with Redux js
 
Vue.js for beginners
Vue.js for beginnersVue.js for beginners
Vue.js for beginners
 
ASP.NET - Life cycle of asp
ASP.NET - Life cycle of aspASP.NET - Life cycle of asp
ASP.NET - Life cycle of asp
 
Reactjs
Reactjs Reactjs
Reactjs
 
Introduction to React JS for beginners
Introduction to React JS for beginners Introduction to React JS for beginners
Introduction to React JS for beginners
 
ASP.NET Tutorial - Presentation 1
ASP.NET Tutorial - Presentation 1ASP.NET Tutorial - Presentation 1
ASP.NET Tutorial - Presentation 1
 
VueJS Introduction
VueJS IntroductionVueJS Introduction
VueJS Introduction
 
Model View Controller (MVC)
Model View Controller (MVC)Model View Controller (MVC)
Model View Controller (MVC)
 
introduction to Vue.js 3
introduction to Vue.js 3 introduction to Vue.js 3
introduction to Vue.js 3
 
ASP.NET Core MVC + Web API with Overview
ASP.NET Core MVC + Web API with OverviewASP.NET Core MVC + Web API with Overview
ASP.NET Core MVC + Web API with Overview
 
Intro to WebSockets
Intro to WebSocketsIntro to WebSockets
Intro to WebSockets
 
The Point of Vue - Intro to Vue.js
The Point of Vue - Intro to Vue.jsThe Point of Vue - Intro to Vue.js
The Point of Vue - Intro to Vue.js
 
Deep dive into Vue.js
Deep dive into Vue.jsDeep dive into Vue.js
Deep dive into Vue.js
 

Andere mochten auch

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
 
Introduction to ASP.NET MVC
Introduction to ASP.NET MVCIntroduction to ASP.NET MVC
Introduction to ASP.NET MVCKhaled Musaied
 
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
 

Andere mochten auch (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
 
Introduction to ASP.NET MVC
Introduction to ASP.NET MVCIntroduction to ASP.NET MVC
Introduction to ASP.NET MVC
 
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
 

Ähnlich wie ASP .net MVC

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
 

Ähnlich wie ASP .net MVC (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
 

Kürzlich hochgeladen

Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 

Kürzlich hochgeladen (20)

Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 

ASP .net MVC

  • 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

Hinweis der Redaktion

  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.