SlideShare a Scribd company logo
Asp.Net MVCA new “pluggable” web frameworkStefano Paluellostefano.paluello@pastesoft.comhttp://stefanopaluello.wordpress.comTwitter: @palutz
MVC and Asp.NetThe Model, the View and the Controller (looks like “The Good, the Bad and the Ugly” )HtmlHelper and PartialViewRoutingFiltersTDD with Asp.Net MVCAgenda
MVC and Asp.NetFrom WebForm to MVC
Asp.NetAsp.Net was introduced in 2002 (.Net 1.0)It was a big improvement from the “spaghetti code” that came with Asp classicIt introduced a new programming model, based on Events, Server-side Controls and “stateful” Form (Session, Cache, ViewState): the RAD/VB-like development model for the web.It allowed a lot of developers to deal with the Web, also if they have limited or no skills at all in HTML and JavaScript.Build with productivity in mind
Windows Form and Web Form modelsServerReactionCodeActionServerHttpRequestSerialize/DeserializeWebform stateCodeHttpResponse
Events and State management are not HTTP concepts (you need a quite big structure to manage them)The page life cycle, with all the events handler, can become really complicated and also delicate (easy to break)You have low control over the HTML code generatedThe complex Unique ID values for the server-side controls don’t fit well with Javascript functionsThere is a fake feeling of separation of concerns with the Asp.Net’s code behindAutomated test could be challenging.That’s cool… But
Web standardsHTTPCSSJavascriptREST (Representational State Transfer), represents an application in terms of resources, instead of SOAP, the Asp.Net web service base technologyAgile and TDDThe Web development today is
So… Welcome, Asp.Net MVCWEB
Asp.Net MVC “tenets”Be extensible, maintainable and flexibleBe testableHave a tight control over HTML and HTTPUse convention over configurationDRY: don’t repeat yourselfSeparation of concerns
The MVC pattern
Separation of concernsSeparation of concerns comes naturally with MVCController knows how to handle a request, that a View exist, and how to use the Model (no more)Model doesn’t know anything about a ViewView doesn’t know there is a Controller
Asp.Net > Asp.Net MVCBased on the .Net platform (quite straightforward  )Master pageForms authenticationMembership and Role providersProfilesInternationalizationCacheAsp.Net MVC is built on (the best part of) Asp.Net
Asp.Net and Asp.Net MVC run-time stack
DemoFirst Asp.NetMVC application
Asp.Net MVCThe structure of the project
Asp.Net MVC projects have some top-level (and core) directories that you don’t need to setup in the config:Controllers, where you put the classes that handle the requestModels, where you put the classes that deal with dataViews, where you put the UI template filesScripts, where you put Javascript library files and scripts (.js)Content, where you put CSS and image files, and so onApp_Data, where you put data filesConvention over configuration
Models, Controllers and Views
The ModelsClasses that represent your application dataContain all the business, validation, and data acccess logic required by your applicationThree different kind of Model: data being posted on the Controllerdata being worked on in the Viewdomain-specific entities from you business tierYou can create your own Data Model leveraging the most recommend data access technologiesThe representation of our data
An actual Data Model using Entity Framework 4.0
ViewModel PatternAdditional layer to abstract the data for the Views from our business tierCan leverage the strongly typed View template featuresThe Controller has to know how to translate from the business tier Entity to the ViewModel oneEnable type safety, compile-time checking and IntellisenseUseful specially in same complex scenariosCreate a class tailored on our specific View scenarios
publicActionResultCustomer(int id){ViewData[“Customer”] = MyRepository.GetCustomerById(id);ViewData[“Orders”] = MyRepository.GetOrderforCustomer(id);return View();}publicclassCustomerOrderMV{Customer CustomerData {get; set;}Order CustomerOrders{ get; set;}}publicActionResult Customer(int id){CustomerOrderMVcustOrd = MyRepository.GetCustomerOrdersById(id);ViewData.Model = custOrd;return View();}Model vs.ViewModel
ValidationValidation and business rule logic are the keys for any application that work with dataSchema validation comes quite free if you use OR/MsValidation and Business Rule logic can be quite easy too using the Asp.Net MVC 2 Data Annotations validation attributes (actually these attributes were introduced as a part of the Asp.Net Dynamic Data)Adding Validation Logic to the Models
[MetadataType(typeof(Blog_Validation))]publicpartialclassBlog{}[Bind(Exclude = "IdBlog")]publicclassBlog_Validation{    [Required(ErrorMessage= "Title required")][StringLength(50, ErrorMessage = "…")][DisplayName("Blog Title")]    publicString Title { get; set; }[Required(ErrorMessage = "Blogger required")][StringLength(50, ErrorMessage = “…")]publicString Blogger { get; set; }ù…}Data Annotations validationHow to add validation to the Model through Metadata
DemoAsp.Net MVC Models
The controllers are responsible for responding to the user requestHave to implement at least the IController interface, but better if you use the ControllerBaseor the Controller abstract classes (with more API and resources, like the ControllerContext and the ViewData, to build your own Controller)The Controllers
using System;usingSystem.Web.Routing;namespaceSystem.Web.Mvc{// Summary:Defines the methods that are required for a controller.publicinterfaceIController    {// Summary: Executes the specified request context.// Parameters://   requestContext:The request context.void Execute(RequestContextrequestContext);    }}usingSystem.Web;usingSystem.Web.Mvc;publicclassSteoController : IController{publicvoid Execute(System.Web.Routing.RequestContextrequestContext)    {HttpResponseBase response = requestContext.HttpContext.Response;response.Write("<h1>Hello MVC World!</h1>");    }}My own Controller
publicinterfaceIHttpHandler{voidProcessRequest(HttpContext context);boolIsReusable { get; }}publicinterfaceIController{voidExecute(RequestContextrequestContext);}They look quite similar, aren’t they?The two methods respond to a request and write back the output to a responseThe Page class, the default base class for ASPX pages in Asp.Net, implements the IHttpHandler.This reminds me something…
The Action MethodsAll the public methods of a Controller class become Action methods, which are callable through an HTTP requestActually, only the public methods according to the defined Routes can be called
The ActionResultActions, as Controller’s methods, have to respond to user input, but they don’t have to manage how to display the outputThe pattern for the Actions is to do their own work and then return an object that derives from the abstract base class ActionResultActionResultadhere to the “Command pattern”, in which commands are methods that you want the framework to perform in your behalf
The ActionResultpublicabstract class ActionResult{public abstract voidExecuteResult(ControllerContext context);}publicActionResultList(){ViewData.Model= // get data from a repositoryreturnView();}
ActionResult typesEmptyResultContentResultJsonResultRedirectResultRedirectToRouteResultViewResultPartialViewResultFileResultFilePathResultFileContentResultFileStreamResultJavaScriptResultAsp.Net MVC has several types to help handle the response
DemoAsp.Net MVC Controllers
The Views are responsible for providing the User Interface (UI) to the userThe View receive a reference to a Model and it transforms the data in a format ready to be presentedThe Views
Asp.Net MVC’s ViewHandles the ViewDataDictionary and translate it into HTML codeIt’s an Asp.Net Page, deriving from ViewPage (System.Web.Mvc.ViewPage) which itself derives from Page (System.Web.UI.Page)By default it doesn’t include the “runat=server”, that you can add by yourself manually, if you want to use some server controls in your View (better to use only the “view-only” controls)Can take advantage of the Master Page, building Views on top of the Asp.Net Page infrastructure
Asp.Net MVC Views’ syntaxYou will use <%: %> syntax (often referred to as “code nuggets”) to execute code within the View template.There are two main ways you will see this used:Code enclosed within <% %> will be executedCode enclosed within <%: %> will be executed, and the result will be output to the page
DemoViews, Strongly Typed View, specify a View
Html HelpersHtml.EncodeHtml.TextBoxHtml.ActionLink, RouteLinkHtml.BeginFormHtml.HiddenHtml.DropDownListHtml.ListBoxHtml.PasswordHtml.RadioButtonHtml.Partial, RenderPartialHtml.Action, RenderActionHtml.TextAreaHtml.ValidationMessageHtml.ValidationSummaryMethods shipped with Asp.Net MVC that help to deal with the HTML code.MVC2 introduced also the strongly typed Helpers, that allow to use Model properties using a Lambda expression instead of a simple string
Partial ViewAsp.Net MVC allow to define partial view templates that can be used to encapsulate view rendering logic once, and then reuse it across an application (help to DRY-up your code)The partial View has a .ascx extension and you can use like a HTML control
The default Asp.Net MVC project just provide you a simple Partial View: the LogOnUserControl.ascx<%@ControlLanguage="C#"Inherits="System.Web.Mvc.ViewUserControl" %><%if (Request.IsAuthenticated) {%>        Welcome <b><%:Page.User.Identity.Name %></b>!        [ <%:Html.ActionLink("Log Off", "LogOff", "Account") %> ]<%    }else {%>         [ <%:Html.ActionLink("Log On", "LogOn", "Account") %> ]<%    }%>Partial View ExampleA simple example out of the box
AjaxYou can use the most popular libraries: Microsoft Asp.Net AjaxjQueryCan help to partial render a complex page (fit well with Partial View)Each Ajax routine will use a dedicated Action on a ControllerWith Asp.Net Ajax you can use the Ajax Helpers that come with Asp.Net MVC:Ajax.BeginFormAjaxOptionsIsAjaxRequest…It’s not really Asp.Net MVC but can really help you to boost your MVC application
RoutingRouting in Asp.Net MVC are used to: Match incoming requests and maps them to a Controller actionConstruct an outgoing URLs that correspond to Contrller actionHow Asp.Net MVC manages the URL
Routing vs URL RewritingThey are both useful approaches in creating separation between the URL and the code that handles the URL, in a SEO (Search Engine Optimization) wayURL rewriting is a page centric view of URLs (eg: /products/redshoes.aspx rewritten as /products/display.aspx?productid=010)Routing is a resource-centric (not only a page) view of URLs. You can look at Routing as a bidirectional URL rewriting
publicstaticvoidRegisterRoutes(RouteCollection routes){routes.IgnoreRoute("{resource}.axd/{*pathInfo}");routes.MapRoute("Default", // Route name"{controller}/{action}/{id}", // URL with parametersnew{ controller = "Home", action = "Index", id = UrlParameter.Optional} // Parameter defaults );}    protectedvoidApplication_Start(){AreaRegistration.RegisterAllAreas();RegisterRoutes(RouteTable.Routes);}}Defining RoutesThe default one…
Route URL patterns
StopRoutingHandler and IgnoreRouteYou can use it when you don’t want to route some particular URLs.Useful when you want to integrate an Asp.Net MVC application with some Asp.Net pages.
FiltersFilters are declarative attribute based means of providing cross-cutting behavior Out of the box action filters provided by Asp.Net MVC:Authorize: to secure the Controller or a Controller ActionHandleError: the action will handle the exceptionsOutputCache: provide output caching to for the action methods
DemoA simple Filter (Session Expire)
TDD with Asp.Net MVCAsp.Net MVC was made with TDD in mind, but you can use also without it (if you want… )A framework designed with TDD in mind from the first stepYou can use your favorite Test FrameworkWith MVC you can test the also your UI behavior (!)
DemoTDD with Asp.Net MVC
Let’s start the Open Session:Asp.Net vs. Asp.Net MVC
Ad

More Related Content

What's hot (20)

Introduction to Spring MVC
Introduction to Spring MVCIntroduction to Spring MVC
Introduction to Spring MVC
Richard Paul
 
Angular - Chapter 1 - Introduction
 Angular - Chapter 1 - Introduction Angular - Chapter 1 - Introduction
Angular - Chapter 1 - Introduction
WebStackAcademy
 
Mvc architecture
Mvc architectureMvc architecture
Mvc architecture
Surbhi Panhalkar
 
React JS .NET
React JS .NETReact JS .NET
React JS .NET
Jennifer Estrada
 
Web sockets in Angular
Web sockets in AngularWeb sockets in Angular
Web sockets in Angular
Yakov Fain
 
Play with Angular JS
Play with Angular JSPlay with Angular JS
Play with Angular JS
Knoldus Inc.
 
Beginning AngularJS
Beginning AngularJSBeginning AngularJS
Beginning AngularJS
Troy Miles
 
Asp.net mvc
Asp.net mvcAsp.net mvc
Asp.net mvc
erdemergin
 
3-TIER ARCHITECTURE IN ASP.NET MVC
3-TIER ARCHITECTURE IN ASP.NET MVC3-TIER ARCHITECTURE IN ASP.NET MVC
3-TIER ARCHITECTURE IN ASP.NET MVC
Mohd Manzoor Ahmed
 
Comparing Angular and React JS for SPAs
Comparing Angular and React JS for SPAsComparing Angular and React JS for SPAs
Comparing Angular and React JS for SPAs
Jennifer Estrada
 
10 practices that every developer needs to start right now
10 practices that every developer needs to start right now10 practices that every developer needs to start right now
10 practices that every developer needs to start right now
Caleb Jenkins
 
Testing Angular
Testing AngularTesting Angular
Testing Angular
Lilia Sfaxi
 
AngularJS Beginner Day One
AngularJS Beginner Day OneAngularJS Beginner Day One
AngularJS Beginner Day One
Troy Miles
 
Spring MVC Architecture Tutorial
Spring MVC Architecture TutorialSpring MVC Architecture Tutorial
Spring MVC Architecture Tutorial
Java Success Point
 
Spring MVC
Spring MVCSpring MVC
Spring MVC
Aaron Schram
 
ASP.NET AJAX with Visual Studio 2008
ASP.NET AJAX with Visual Studio 2008ASP.NET AJAX with Visual Studio 2008
ASP.NET AJAX with Visual Studio 2008
Caleb Jenkins
 
Angular 4
Angular 4Angular 4
Angular 4
Saurabh Juneja
 
Angular Data Binding
Angular Data BindingAngular Data Binding
Angular Data Binding
Jennifer Estrada
 
Angular View Encapsulation
Angular View EncapsulationAngular View Encapsulation
Angular View Encapsulation
Jennifer Estrada
 
Web Performance & Latest in React
Web Performance & Latest in ReactWeb Performance & Latest in React
Web Performance & Latest in React
Talentica Software
 
Introduction to Spring MVC
Introduction to Spring MVCIntroduction to Spring MVC
Introduction to Spring MVC
Richard Paul
 
Angular - Chapter 1 - Introduction
 Angular - Chapter 1 - Introduction Angular - Chapter 1 - Introduction
Angular - Chapter 1 - Introduction
WebStackAcademy
 
Web sockets in Angular
Web sockets in AngularWeb sockets in Angular
Web sockets in Angular
Yakov Fain
 
Play with Angular JS
Play with Angular JSPlay with Angular JS
Play with Angular JS
Knoldus Inc.
 
Beginning AngularJS
Beginning AngularJSBeginning AngularJS
Beginning AngularJS
Troy Miles
 
3-TIER ARCHITECTURE IN ASP.NET MVC
3-TIER ARCHITECTURE IN ASP.NET MVC3-TIER ARCHITECTURE IN ASP.NET MVC
3-TIER ARCHITECTURE IN ASP.NET MVC
Mohd Manzoor Ahmed
 
Comparing Angular and React JS for SPAs
Comparing Angular and React JS for SPAsComparing Angular and React JS for SPAs
Comparing Angular and React JS for SPAs
Jennifer Estrada
 
10 practices that every developer needs to start right now
10 practices that every developer needs to start right now10 practices that every developer needs to start right now
10 practices that every developer needs to start right now
Caleb Jenkins
 
AngularJS Beginner Day One
AngularJS Beginner Day OneAngularJS Beginner Day One
AngularJS Beginner Day One
Troy Miles
 
Spring MVC Architecture Tutorial
Spring MVC Architecture TutorialSpring MVC Architecture Tutorial
Spring MVC Architecture Tutorial
Java Success Point
 
ASP.NET AJAX with Visual Studio 2008
ASP.NET AJAX with Visual Studio 2008ASP.NET AJAX with Visual Studio 2008
ASP.NET AJAX with Visual Studio 2008
Caleb Jenkins
 
Angular View Encapsulation
Angular View EncapsulationAngular View Encapsulation
Angular View Encapsulation
Jennifer Estrada
 
Web Performance & Latest in React
Web Performance & Latest in ReactWeb Performance & Latest in React
Web Performance & Latest in React
Talentica Software
 

Viewers also liked (19)

Introduction to ASP.NET MVC
Introduction to ASP.NET MVCIntroduction to ASP.NET MVC
Introduction to ASP.NET MVC
Khaled Musaied
 
RESTful apps and services with ASP.NET MVC
RESTful apps and services with ASP.NET MVCRESTful apps and services with ASP.NET MVC
RESTful apps and services with ASP.NET MVC
bnoyle
 
TDD with Visual Studio 2010
TDD with Visual Studio 2010TDD with Visual Studio 2010
TDD with Visual Studio 2010
Stefano Paluello
 
Windows Azure Overview
Windows Azure OverviewWindows Azure Overview
Windows Azure Overview
Stefano Paluello
 
Entity Framework 4
Entity Framework 4Entity Framework 4
Entity Framework 4
Stefano Paluello
 
Learning ASP.NET 5 and MVC 6
Learning ASP.NET 5 and MVC 6Learning ASP.NET 5 and MVC 6
Learning ASP.NET 5 and MVC 6
Ido Flatow
 
Real scenario: moving a legacy app to the Cloud
Real scenario: moving a legacy app to the CloudReal scenario: moving a legacy app to the Cloud
Real scenario: moving a legacy app to the Cloud
Stefano Paluello
 
Getting Started with ASP.NET MVC
Getting Started with ASP.NET MVCGetting Started with ASP.NET MVC
Getting Started with ASP.NET MVC
shobokshi
 
ASP.NET MVC Best Practices malisa ncube
ASP.NET MVC Best Practices   malisa ncubeASP.NET MVC Best Practices   malisa ncube
ASP.NET MVC Best Practices malisa ncube
Malisa Ncube
 
Quoi de neuf dans ASP.NET MVC 4
Quoi de neuf dans ASP.NET MVC 4Quoi de neuf dans ASP.NET MVC 4
Quoi de neuf dans ASP.NET MVC 4
Microsoft
 
ASP.NET MVC 5 et Web API 2
ASP.NET MVC 5 et Web API 2ASP.NET MVC 5 et Web API 2
ASP.NET MVC 5 et Web API 2
Microsoft
 
ASP.NET MVC 6
ASP.NET MVC 6ASP.NET MVC 6
ASP.NET MVC 6
Microsoft
 
70 533 - Module 01 - Introduction to Azure
70 533 - Module 01 - Introduction to Azure70 533 - Module 01 - Introduction to Azure
70 533 - Module 01 - Introduction to Azure
Georges-Emmanuel TOPE
 
Ebook 70 533 implementing microsoft infrastructure solution
Ebook 70 533 implementing microsoft infrastructure solutionEbook 70 533 implementing microsoft infrastructure solution
Ebook 70 533 implementing microsoft infrastructure solution
Mahesh Dahal
 
C#.net
C#.netC#.net
C#.net
vnboghani
 
Top 9 c#.net interview questions answers
Top 9 c#.net interview questions answersTop 9 c#.net interview questions answers
Top 9 c#.net interview questions answers
Jobinterviews
 
MVC 6 Introduction
MVC 6 IntroductionMVC 6 Introduction
MVC 6 Introduction
Sudhakar Sharma
 
ASP.NET Brief History
ASP.NET Brief HistoryASP.NET Brief History
ASP.NET Brief History
Sudhakar Sharma
 
Dotnet Basics Presentation
Dotnet Basics PresentationDotnet Basics Presentation
Dotnet Basics Presentation
Sudhakar Sharma
 
Introduction to ASP.NET MVC
Introduction to ASP.NET MVCIntroduction to ASP.NET MVC
Introduction to ASP.NET MVC
Khaled Musaied
 
RESTful apps and services with ASP.NET MVC
RESTful apps and services with ASP.NET MVCRESTful apps and services with ASP.NET MVC
RESTful apps and services with ASP.NET MVC
bnoyle
 
TDD with Visual Studio 2010
TDD with Visual Studio 2010TDD with Visual Studio 2010
TDD with Visual Studio 2010
Stefano Paluello
 
Learning ASP.NET 5 and MVC 6
Learning ASP.NET 5 and MVC 6Learning ASP.NET 5 and MVC 6
Learning ASP.NET 5 and MVC 6
Ido Flatow
 
Real scenario: moving a legacy app to the Cloud
Real scenario: moving a legacy app to the CloudReal scenario: moving a legacy app to the Cloud
Real scenario: moving a legacy app to the Cloud
Stefano Paluello
 
Getting Started with ASP.NET MVC
Getting Started with ASP.NET MVCGetting Started with ASP.NET MVC
Getting Started with ASP.NET MVC
shobokshi
 
ASP.NET MVC Best Practices malisa ncube
ASP.NET MVC Best Practices   malisa ncubeASP.NET MVC Best Practices   malisa ncube
ASP.NET MVC Best Practices malisa ncube
Malisa Ncube
 
Quoi de neuf dans ASP.NET MVC 4
Quoi de neuf dans ASP.NET MVC 4Quoi de neuf dans ASP.NET MVC 4
Quoi de neuf dans ASP.NET MVC 4
Microsoft
 
ASP.NET MVC 5 et Web API 2
ASP.NET MVC 5 et Web API 2ASP.NET MVC 5 et Web API 2
ASP.NET MVC 5 et Web API 2
Microsoft
 
ASP.NET MVC 6
ASP.NET MVC 6ASP.NET MVC 6
ASP.NET MVC 6
Microsoft
 
70 533 - Module 01 - Introduction to Azure
70 533 - Module 01 - Introduction to Azure70 533 - Module 01 - Introduction to Azure
70 533 - Module 01 - Introduction to Azure
Georges-Emmanuel TOPE
 
Ebook 70 533 implementing microsoft infrastructure solution
Ebook 70 533 implementing microsoft infrastructure solutionEbook 70 533 implementing microsoft infrastructure solution
Ebook 70 533 implementing microsoft infrastructure solution
Mahesh Dahal
 
Top 9 c#.net interview questions answers
Top 9 c#.net interview questions answersTop 9 c#.net interview questions answers
Top 9 c#.net interview questions answers
Jobinterviews
 
Dotnet Basics Presentation
Dotnet Basics PresentationDotnet Basics Presentation
Dotnet Basics Presentation
Sudhakar Sharma
 
Ad

Similar to Asp.Net MVC Intro (20)

Introduction To Mvc
Introduction To MvcIntroduction To Mvc
Introduction To Mvc
Volkan Uzun
 
Asp.net mvc
Asp.net mvcAsp.net mvc
Asp.net mvc
Phuc Le Cong
 
MVC From Beginner to Advance in Indian Style by - Indiandotnet
MVC From Beginner to Advance in Indian Style by - IndiandotnetMVC From Beginner to Advance in Indian Style by - Indiandotnet
MVC From Beginner to Advance in Indian Style by - Indiandotnet
Indiandotnet
 
ASP.NET MVC Presentation
ASP.NET MVC PresentationASP.NET MVC Presentation
ASP.NET MVC Presentation
ivpol
 
ASP.NET MVC introduction
ASP.NET MVC introductionASP.NET MVC introduction
ASP.NET MVC introduction
Tomi Juhola
 
ASP.net MVC CodeCamp Presentation
ASP.net MVC CodeCamp PresentationASP.net MVC CodeCamp Presentation
ASP.net MVC CodeCamp Presentation
buildmaster
 
SoftServe - "ASP.NET MVC як наступний крок у розвитку технології розробки Web...
SoftServe - "ASP.NET MVC як наступний крок у розвитку технології розробки Web...SoftServe - "ASP.NET MVC як наступний крок у розвитку технології розробки Web...
SoftServe - "ASP.NET MVC як наступний крок у розвитку технології розробки Web...
SoftServe
 
Introduction to ASP.NET MVC
Introduction to ASP.NET MVCIntroduction to ASP.NET MVC
Introduction to ASP.NET MVC
Sunpawet Somsin
 
MVC 4
MVC 4MVC 4
MVC 4
Vasilios Kuznos
 
ASP .NET MVC
ASP .NET MVC ASP .NET MVC
ASP .NET MVC
eldorina
 
Simple mvc4 prepared by gigin krishnan
Simple mvc4 prepared by gigin krishnanSimple mvc4 prepared by gigin krishnan
Simple mvc4 prepared by gigin krishnan
Gigin Krishnan
 
MVC ppt presentation
MVC ppt presentationMVC ppt presentation
MVC ppt presentation
Bhavin Shah
 
ASP.NET MVC Presentation
ASP.NET MVC PresentationASP.NET MVC Presentation
ASP.NET MVC Presentation
Volkan Uzun
 
Getting Started with Zend Framework
Getting Started with Zend FrameworkGetting Started with Zend Framework
Getting Started with Zend Framework
Juan Antonio
 
Adding a view
Adding a viewAdding a view
Adding a view
Nhan Do
 
ASP.NET MVC Fundamental
ASP.NET MVC FundamentalASP.NET MVC Fundamental
ASP.NET MVC Fundamental
ldcphuc
 
MVC
MVCMVC
MVC
akshin
 
Asp.net mvc
Asp.net mvcAsp.net mvc
Asp.net mvc
Taranjeet Singh
 
Jinal desai .net
Jinal desai .netJinal desai .net
Jinal desai .net
rohitkumar1987in
 
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
goodfriday
 
Introduction To Mvc
Introduction To MvcIntroduction To Mvc
Introduction To Mvc
Volkan Uzun
 
MVC From Beginner to Advance in Indian Style by - Indiandotnet
MVC From Beginner to Advance in Indian Style by - IndiandotnetMVC From Beginner to Advance in Indian Style by - Indiandotnet
MVC From Beginner to Advance in Indian Style by - Indiandotnet
Indiandotnet
 
ASP.NET MVC Presentation
ASP.NET MVC PresentationASP.NET MVC Presentation
ASP.NET MVC Presentation
ivpol
 
ASP.NET MVC introduction
ASP.NET MVC introductionASP.NET MVC introduction
ASP.NET MVC introduction
Tomi Juhola
 
ASP.net MVC CodeCamp Presentation
ASP.net MVC CodeCamp PresentationASP.net MVC CodeCamp Presentation
ASP.net MVC CodeCamp Presentation
buildmaster
 
SoftServe - "ASP.NET MVC як наступний крок у розвитку технології розробки Web...
SoftServe - "ASP.NET MVC як наступний крок у розвитку технології розробки Web...SoftServe - "ASP.NET MVC як наступний крок у розвитку технології розробки Web...
SoftServe - "ASP.NET MVC як наступний крок у розвитку технології розробки Web...
SoftServe
 
Introduction to ASP.NET MVC
Introduction to ASP.NET MVCIntroduction to ASP.NET MVC
Introduction to ASP.NET MVC
Sunpawet Somsin
 
ASP .NET MVC
ASP .NET MVC ASP .NET MVC
ASP .NET MVC
eldorina
 
Simple mvc4 prepared by gigin krishnan
Simple mvc4 prepared by gigin krishnanSimple mvc4 prepared by gigin krishnan
Simple mvc4 prepared by gigin krishnan
Gigin Krishnan
 
MVC ppt presentation
MVC ppt presentationMVC ppt presentation
MVC ppt presentation
Bhavin Shah
 
ASP.NET MVC Presentation
ASP.NET MVC PresentationASP.NET MVC Presentation
ASP.NET MVC Presentation
Volkan Uzun
 
Getting Started with Zend Framework
Getting Started with Zend FrameworkGetting Started with Zend Framework
Getting Started with Zend Framework
Juan Antonio
 
Adding a view
Adding a viewAdding a view
Adding a view
Nhan Do
 
ASP.NET MVC Fundamental
ASP.NET MVC FundamentalASP.NET MVC Fundamental
ASP.NET MVC Fundamental
ldcphuc
 
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
goodfriday
 
Ad

More from Stefano Paluello (6)

Clinical Data and AI
Clinical Data and AIClinical Data and AI
Clinical Data and AI
Stefano Paluello
 
A gentle introduction to the world of BigData and Hadoop
A gentle introduction to the world of BigData and HadoopA gentle introduction to the world of BigData and Hadoop
A gentle introduction to the world of BigData and Hadoop
Stefano Paluello
 
Grandata
GrandataGrandata
Grandata
Stefano Paluello
 
Using MongoDB with the .Net Framework
Using MongoDB with the .Net FrameworkUsing MongoDB with the .Net Framework
Using MongoDB with the .Net Framework
Stefano Paluello
 
Teamwork and agile methodologies
Teamwork and agile methodologiesTeamwork and agile methodologies
Teamwork and agile methodologies
Stefano Paluello
 
A gentle introduction to the world of BigData and Hadoop
A gentle introduction to the world of BigData and HadoopA gentle introduction to the world of BigData and Hadoop
A gentle introduction to the world of BigData and Hadoop
Stefano Paluello
 
Using MongoDB with the .Net Framework
Using MongoDB with the .Net FrameworkUsing MongoDB with the .Net Framework
Using MongoDB with the .Net Framework
Stefano Paluello
 
Teamwork and agile methodologies
Teamwork and agile methodologiesTeamwork and agile methodologies
Teamwork and agile methodologies
Stefano Paluello
 

Recently uploaded (20)

SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
Learn the Basics of Agile Development: Your Step-by-Step Guide
Learn the Basics of Agile Development: Your Step-by-Step GuideLearn the Basics of Agile Development: Your Step-by-Step Guide
Learn the Basics of Agile Development: Your Step-by-Step Guide
Marcel David
 
"PHP and MySQL CRUD Operations for Student Management System"
"PHP and MySQL CRUD Operations for Student Management System""PHP and MySQL CRUD Operations for Student Management System"
"PHP and MySQL CRUD Operations for Student Management System"
Jainul Musani
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
"Rebranding for Growth", Anna Velykoivanenko
"Rebranding for Growth", Anna Velykoivanenko"Rebranding for Growth", Anna Velykoivanenko
"Rebranding for Growth", Anna Velykoivanenko
Fwdays
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
"Client Partnership — the Path to Exponential Growth for Companies Sized 50-5...
"Client Partnership — the Path to Exponential Growth for Companies Sized 50-5..."Client Partnership — the Path to Exponential Growth for Companies Sized 50-5...
"Client Partnership — the Path to Exponential Growth for Companies Sized 50-5...
Fwdays
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
Rock, Paper, Scissors: An Apex Map Learning Journey
Rock, Paper, Scissors: An Apex Map Learning JourneyRock, Paper, Scissors: An Apex Map Learning Journey
Rock, Paper, Scissors: An Apex Map Learning Journey
Lynda Kane
 
Salesforce AI Associate 2 of 2 Certification.docx
Salesforce AI Associate 2 of 2 Certification.docxSalesforce AI Associate 2 of 2 Certification.docx
Salesforce AI Associate 2 of 2 Certification.docx
José Enrique López Rivera
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
Network Security. Different aspects of Network Security.
Network Security. Different aspects of Network Security.Network Security. Different aspects of Network Security.
Network Security. Different aspects of Network Security.
gregtap1
 
Leading AI Innovation As A Product Manager - Michael Jidael
Leading AI Innovation As A Product Manager - Michael JidaelLeading AI Innovation As A Product Manager - Michael Jidael
Leading AI Innovation As A Product Manager - Michael Jidael
Michael Jidael
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
Learn the Basics of Agile Development: Your Step-by-Step Guide
Learn the Basics of Agile Development: Your Step-by-Step GuideLearn the Basics of Agile Development: Your Step-by-Step Guide
Learn the Basics of Agile Development: Your Step-by-Step Guide
Marcel David
 
"PHP and MySQL CRUD Operations for Student Management System"
"PHP and MySQL CRUD Operations for Student Management System""PHP and MySQL CRUD Operations for Student Management System"
"PHP and MySQL CRUD Operations for Student Management System"
Jainul Musani
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
"Rebranding for Growth", Anna Velykoivanenko
"Rebranding for Growth", Anna Velykoivanenko"Rebranding for Growth", Anna Velykoivanenko
"Rebranding for Growth", Anna Velykoivanenko
Fwdays
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
"Client Partnership — the Path to Exponential Growth for Companies Sized 50-5...
"Client Partnership — the Path to Exponential Growth for Companies Sized 50-5..."Client Partnership — the Path to Exponential Growth for Companies Sized 50-5...
"Client Partnership — the Path to Exponential Growth for Companies Sized 50-5...
Fwdays
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
Rock, Paper, Scissors: An Apex Map Learning Journey
Rock, Paper, Scissors: An Apex Map Learning JourneyRock, Paper, Scissors: An Apex Map Learning Journey
Rock, Paper, Scissors: An Apex Map Learning Journey
Lynda Kane
 
Salesforce AI Associate 2 of 2 Certification.docx
Salesforce AI Associate 2 of 2 Certification.docxSalesforce AI Associate 2 of 2 Certification.docx
Salesforce AI Associate 2 of 2 Certification.docx
José Enrique López Rivera
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
Network Security. Different aspects of Network Security.
Network Security. Different aspects of Network Security.Network Security. Different aspects of Network Security.
Network Security. Different aspects of Network Security.
gregtap1
 
Leading AI Innovation As A Product Manager - Michael Jidael
Leading AI Innovation As A Product Manager - Michael JidaelLeading AI Innovation As A Product Manager - Michael Jidael
Leading AI Innovation As A Product Manager - Michael Jidael
Michael Jidael
 

Asp.Net MVC Intro

  • 1. Asp.Net MVCA new “pluggable” web frameworkStefano [email protected]://stefanopaluello.wordpress.comTwitter: @palutz
  • 2. MVC and Asp.NetThe Model, the View and the Controller (looks like “The Good, the Bad and the Ugly” )HtmlHelper and PartialViewRoutingFiltersTDD with Asp.Net MVCAgenda
  • 3. MVC and Asp.NetFrom WebForm to MVC
  • 4. Asp.NetAsp.Net was introduced in 2002 (.Net 1.0)It was a big improvement from the “spaghetti code” that came with Asp classicIt introduced a new programming model, based on Events, Server-side Controls and “stateful” Form (Session, Cache, ViewState): the RAD/VB-like development model for the web.It allowed a lot of developers to deal with the Web, also if they have limited or no skills at all in HTML and JavaScript.Build with productivity in mind
  • 5. Windows Form and Web Form modelsServerReactionCodeActionServerHttpRequestSerialize/DeserializeWebform stateCodeHttpResponse
  • 6. Events and State management are not HTTP concepts (you need a quite big structure to manage them)The page life cycle, with all the events handler, can become really complicated and also delicate (easy to break)You have low control over the HTML code generatedThe complex Unique ID values for the server-side controls don’t fit well with Javascript functionsThere is a fake feeling of separation of concerns with the Asp.Net’s code behindAutomated test could be challenging.That’s cool… But
  • 7. Web standardsHTTPCSSJavascriptREST (Representational State Transfer), represents an application in terms of resources, instead of SOAP, the Asp.Net web service base technologyAgile and TDDThe Web development today is
  • 9. Asp.Net MVC “tenets”Be extensible, maintainable and flexibleBe testableHave a tight control over HTML and HTTPUse convention over configurationDRY: don’t repeat yourselfSeparation of concerns
  • 11. Separation of concernsSeparation of concerns comes naturally with MVCController knows how to handle a request, that a View exist, and how to use the Model (no more)Model doesn’t know anything about a ViewView doesn’t know there is a Controller
  • 12. Asp.Net > Asp.Net MVCBased on the .Net platform (quite straightforward  )Master pageForms authenticationMembership and Role providersProfilesInternationalizationCacheAsp.Net MVC is built on (the best part of) Asp.Net
  • 13. Asp.Net and Asp.Net MVC run-time stack
  • 15. Asp.Net MVCThe structure of the project
  • 16. Asp.Net MVC projects have some top-level (and core) directories that you don’t need to setup in the config:Controllers, where you put the classes that handle the requestModels, where you put the classes that deal with dataViews, where you put the UI template filesScripts, where you put Javascript library files and scripts (.js)Content, where you put CSS and image files, and so onApp_Data, where you put data filesConvention over configuration
  • 18. The ModelsClasses that represent your application dataContain all the business, validation, and data acccess logic required by your applicationThree different kind of Model: data being posted on the Controllerdata being worked on in the Viewdomain-specific entities from you business tierYou can create your own Data Model leveraging the most recommend data access technologiesThe representation of our data
  • 19. An actual Data Model using Entity Framework 4.0
  • 20. ViewModel PatternAdditional layer to abstract the data for the Views from our business tierCan leverage the strongly typed View template featuresThe Controller has to know how to translate from the business tier Entity to the ViewModel oneEnable type safety, compile-time checking and IntellisenseUseful specially in same complex scenariosCreate a class tailored on our specific View scenarios
  • 21. publicActionResultCustomer(int id){ViewData[“Customer”] = MyRepository.GetCustomerById(id);ViewData[“Orders”] = MyRepository.GetOrderforCustomer(id);return View();}publicclassCustomerOrderMV{Customer CustomerData {get; set;}Order CustomerOrders{ get; set;}}publicActionResult Customer(int id){CustomerOrderMVcustOrd = MyRepository.GetCustomerOrdersById(id);ViewData.Model = custOrd;return View();}Model vs.ViewModel
  • 22. ValidationValidation and business rule logic are the keys for any application that work with dataSchema validation comes quite free if you use OR/MsValidation and Business Rule logic can be quite easy too using the Asp.Net MVC 2 Data Annotations validation attributes (actually these attributes were introduced as a part of the Asp.Net Dynamic Data)Adding Validation Logic to the Models
  • 23. [MetadataType(typeof(Blog_Validation))]publicpartialclassBlog{}[Bind(Exclude = "IdBlog")]publicclassBlog_Validation{ [Required(ErrorMessage= "Title required")][StringLength(50, ErrorMessage = "…")][DisplayName("Blog Title")] publicString Title { get; set; }[Required(ErrorMessage = "Blogger required")][StringLength(50, ErrorMessage = “…")]publicString Blogger { get; set; }ù…}Data Annotations validationHow to add validation to the Model through Metadata
  • 25. The controllers are responsible for responding to the user requestHave to implement at least the IController interface, but better if you use the ControllerBaseor the Controller abstract classes (with more API and resources, like the ControllerContext and the ViewData, to build your own Controller)The Controllers
  • 26. using System;usingSystem.Web.Routing;namespaceSystem.Web.Mvc{// Summary:Defines the methods that are required for a controller.publicinterfaceIController {// Summary: Executes the specified request context.// Parameters:// requestContext:The request context.void Execute(RequestContextrequestContext); }}usingSystem.Web;usingSystem.Web.Mvc;publicclassSteoController : IController{publicvoid Execute(System.Web.Routing.RequestContextrequestContext) {HttpResponseBase response = requestContext.HttpContext.Response;response.Write("<h1>Hello MVC World!</h1>"); }}My own Controller
  • 27. publicinterfaceIHttpHandler{voidProcessRequest(HttpContext context);boolIsReusable { get; }}publicinterfaceIController{voidExecute(RequestContextrequestContext);}They look quite similar, aren’t they?The two methods respond to a request and write back the output to a responseThe Page class, the default base class for ASPX pages in Asp.Net, implements the IHttpHandler.This reminds me something…
  • 28. The Action MethodsAll the public methods of a Controller class become Action methods, which are callable through an HTTP requestActually, only the public methods according to the defined Routes can be called
  • 29. The ActionResultActions, as Controller’s methods, have to respond to user input, but they don’t have to manage how to display the outputThe pattern for the Actions is to do their own work and then return an object that derives from the abstract base class ActionResultActionResultadhere to the “Command pattern”, in which commands are methods that you want the framework to perform in your behalf
  • 30. The ActionResultpublicabstract class ActionResult{public abstract voidExecuteResult(ControllerContext context);}publicActionResultList(){ViewData.Model= // get data from a repositoryreturnView();}
  • 33. The Views are responsible for providing the User Interface (UI) to the userThe View receive a reference to a Model and it transforms the data in a format ready to be presentedThe Views
  • 34. Asp.Net MVC’s ViewHandles the ViewDataDictionary and translate it into HTML codeIt’s an Asp.Net Page, deriving from ViewPage (System.Web.Mvc.ViewPage) which itself derives from Page (System.Web.UI.Page)By default it doesn’t include the “runat=server”, that you can add by yourself manually, if you want to use some server controls in your View (better to use only the “view-only” controls)Can take advantage of the Master Page, building Views on top of the Asp.Net Page infrastructure
  • 35. Asp.Net MVC Views’ syntaxYou will use <%: %> syntax (often referred to as “code nuggets”) to execute code within the View template.There are two main ways you will see this used:Code enclosed within <% %> will be executedCode enclosed within <%: %> will be executed, and the result will be output to the page
  • 36. DemoViews, Strongly Typed View, specify a View
  • 37. Html HelpersHtml.EncodeHtml.TextBoxHtml.ActionLink, RouteLinkHtml.BeginFormHtml.HiddenHtml.DropDownListHtml.ListBoxHtml.PasswordHtml.RadioButtonHtml.Partial, RenderPartialHtml.Action, RenderActionHtml.TextAreaHtml.ValidationMessageHtml.ValidationSummaryMethods shipped with Asp.Net MVC that help to deal with the HTML code.MVC2 introduced also the strongly typed Helpers, that allow to use Model properties using a Lambda expression instead of a simple string
  • 38. Partial ViewAsp.Net MVC allow to define partial view templates that can be used to encapsulate view rendering logic once, and then reuse it across an application (help to DRY-up your code)The partial View has a .ascx extension and you can use like a HTML control
  • 39. The default Asp.Net MVC project just provide you a simple Partial View: the LogOnUserControl.ascx<%@ControlLanguage="C#"Inherits="System.Web.Mvc.ViewUserControl" %><%if (Request.IsAuthenticated) {%> Welcome <b><%:Page.User.Identity.Name %></b>! [ <%:Html.ActionLink("Log Off", "LogOff", "Account") %> ]<% }else {%> [ <%:Html.ActionLink("Log On", "LogOn", "Account") %> ]<% }%>Partial View ExampleA simple example out of the box
  • 40. AjaxYou can use the most popular libraries: Microsoft Asp.Net AjaxjQueryCan help to partial render a complex page (fit well with Partial View)Each Ajax routine will use a dedicated Action on a ControllerWith Asp.Net Ajax you can use the Ajax Helpers that come with Asp.Net MVC:Ajax.BeginFormAjaxOptionsIsAjaxRequest…It’s not really Asp.Net MVC but can really help you to boost your MVC application
  • 41. RoutingRouting in Asp.Net MVC are used to: Match incoming requests and maps them to a Controller actionConstruct an outgoing URLs that correspond to Contrller actionHow Asp.Net MVC manages the URL
  • 42. Routing vs URL RewritingThey are both useful approaches in creating separation between the URL and the code that handles the URL, in a SEO (Search Engine Optimization) wayURL rewriting is a page centric view of URLs (eg: /products/redshoes.aspx rewritten as /products/display.aspx?productid=010)Routing is a resource-centric (not only a page) view of URLs. You can look at Routing as a bidirectional URL rewriting
  • 43. publicstaticvoidRegisterRoutes(RouteCollection routes){routes.IgnoreRoute("{resource}.axd/{*pathInfo}");routes.MapRoute("Default", // Route name"{controller}/{action}/{id}", // URL with parametersnew{ controller = "Home", action = "Index", id = UrlParameter.Optional} // Parameter defaults );} protectedvoidApplication_Start(){AreaRegistration.RegisterAllAreas();RegisterRoutes(RouteTable.Routes);}}Defining RoutesThe default one…
  • 45. StopRoutingHandler and IgnoreRouteYou can use it when you don’t want to route some particular URLs.Useful when you want to integrate an Asp.Net MVC application with some Asp.Net pages.
  • 46. FiltersFilters are declarative attribute based means of providing cross-cutting behavior Out of the box action filters provided by Asp.Net MVC:Authorize: to secure the Controller or a Controller ActionHandleError: the action will handle the exceptionsOutputCache: provide output caching to for the action methods
  • 47. DemoA simple Filter (Session Expire)
  • 48. TDD with Asp.Net MVCAsp.Net MVC was made with TDD in mind, but you can use also without it (if you want… )A framework designed with TDD in mind from the first stepYou can use your favorite Test FrameworkWith MVC you can test the also your UI behavior (!)
  • 50. Let’s start the Open Session:Asp.Net vs. Asp.Net MVC