SlideShare una empresa de Scribd logo
1 de 38
ASP.NET MVC  Mahesh Sikakolli
MVC Pattern A architectural design pattern used in software engineering Acronym for Model ● View ● Controller Often seen in web applications but not limited to it Def Isolate the business logic  from input and presentation,  permitting independent development,  testing and maintenance of each. Separation of concerns
Roles and Communication
WebForms are great … WebForms are great … Mature, proven technology Scalable Extensible Familiar feel to WinForms developers Lot of features like viewstate , rich controls support, page life cycle … but they have challenges Abstractions aren’t very abstract Difficult to test Lack of control over markup It does things you didn’t tell it to do Slow because of controls and page cycles
ASP.NET MVC Framework Goals Utilize ASP.NET architecture. Testability  Loosely Coupled and extensible Tight control over markup User/SEO friendly URLs Adopt REST concepts Leverage the benefits of ASP.NET Separation of concerns SRP – Single Responsibility Principle DRY – Don’t Repeat Yourself  -Changes are limited to one place Helps with concurrent development Convention over configuration
What happend to Webforms Not a replacement for WebForms All about alternatives Fundamental Part of the System.Web namespace Same team that builds WebForms Providers still work Membership, Caching, Session, etc. Views leverage .aspx and .ascx But they don’t have to if you don’t want them to Feature Sharing
What is ASP.NET MVC? Controller Request Step 1 Incoming request directed to Controller
Model What is ASP.NET MVC? Controller Step 2 Controller processes request and forms a data Model
View What is ASP.NET MVC? Controller View Step 3 Model is passed to View
View What is ASP.NET MVC? Controller View Step 4 View transforms Model into appropriate output format
What is ASP.NET MVC? Controller View Response Step 5 Response is rendered
ModelVC Model represents the business objects, the data of the application. Apart from giving the data objects, it doesn’t have significance in the framework You can use any of the following technologies to  build model objects LINQ to Entities,  LINQ to SQL, NHibernate, LLBLGen Pro, SubSonic, WilsonORM just raw ADO.NET DataReaders or DataSets.
MVController Controller is the core component in MVC  which intercepts and process the requests with the help of views and models Every controller has one or more Action methods. All requests are mapped to a public methods in a controller are called Actions Controller and its Action methods not exposed to outside, but mapped with corresponding routes. A controller is a class extended from abstract System.Web.Mvc.Controller or Icontroller. All the controllers should be available in a folder by name controllers. Controller naming standard should be “nameController” Routing handler will look for the named controller in routing collection and handovers the request to the controller/action. Every controller has ControllerContext(RequestContext+HttpContext) Every controller has virtual methods which can be override  OnActionExecuted,  OnAuthorization,  OnException,  OnResultExecuting
MViewC Views are the end user interface elements/Html templates of the application. View pages are not exposed outside. Views are returned from Action methods using overload view methods of controller  Return View(); return View(“NotIndex”);  return View(“~/Some/Other/View.aspx”); View(products) View and controller share the date with viewData Views page are extended from ASP.NET Page object. Can have server code with <% %> and client side code. Two types of views StronglyTyped Model object is available to access  strongly typed object  Inherits from  System.Web.Mvc.ViewPage<Model> Generic view  ViewData object is available to access  ViewDataDictionary Inherits from System.Web.Mvc.ViewPage Generally views are available in “viewsontrollername” folder  Views supports usercontrols and masterpages. WebFormViewEngine Can I use both model and viewdata same time?s
Action method Typically Action method will communicate with business logic tire and get the actual data to be rendered. Every public method in a Controller is a Action method. By default every action method is mapped to the view with same name in the viewsontroller folder.  Method can contain parameters, Parameters are passed by the urls (or) generic View (or) Model Binders incase of strongly typed views  /Products/List/car  (or)   /Products/List?name=car Every method will return a instance of abstract class ActionResultor a derived class Not every methods members are Action methods If a method is with NonActionAttribute Special methods such as constructors, property assessors, and event assessors cannot be action methods. Methods originally defined on Object (such as ToString)
ActionResult Every method will return a class that derived from ActionResult abstract base class ActionResultwill handle framework level work (where as Action methods will handle application logic) Lot of helper methods are available in controller  for returning ActionResult instances You can also instantiate and return a ActionResult .new ViewResult {ViewData = this.ViewData }; Its not compulsory to return a ActionResult. But you can return the string datatype. But it uses the ContentResult to return the actual data by converting to a string datatype. You can create your own ActionResult public abstract class ActionResult { 		public abstract void ExecuteResult(ControllerContext context); }
ActionResult Types
HTML Helper methods Set of methods which helps to generate the basic html. They works with Routing Engine and MVC Features(like validation) There are times when you don’t want to be in control over the markup. All defined in System.Web.Mvc.Html. Extension methods are in HtmlHelper class  HtmlHelper class which is exposed by Viewpage.HTML() Set of common patters All helpers attribute encode attribute values. Automatic binding of values with the values in the ModelStatedictionary. The name argument to the helper is used as the key to the dictionary. If the ModelStatecontains an error, the form helper associated with that error will render a CSS class of “input-validation-error” in addition to any explicitly specified CSS classes.  Different types of HTML Helpers are available(check in object Browser) Also supports rendering partial views(user controls)
Validation You find the errors in the controller, how do you propagate them to the view? The answer is System.Web.Mvc.ModelStateDictionary ,ModelState Process You have to add all error messages to ModelstateDictionary in Action method Html.ValidationMessage(“name”) Html.ValidationMessage(“Key” ,  ”Custom Error Message”) class=” field-validation-error” is used to show the message Html.ValidationSummary(“custom message”) Displays unordered list of all validation errors in the ModelState dictionary class=”validation-summary-errors” is used to format which is available in template Do not confuse the Model(ViewDataDictionary) object in a view with ModelState(ModelStateDictionary) in a controller  The default model binder supports the use of objects that implement ComponentModels.IDataErrorInfo
Model Binders These are user defined classes  Used to define the strongly typed views of model objects To make easy of handling HTTP Post requests and helps in populating the parameters in action methods. Models are passed between Action method Strongly Typed Views Use attribute to override model binding  Bind(Exclude:="Id") How? Incoming data is automatically parsed and used to populate action method parameters by matching incoming key/value pairs of the http request with the names of properties on the desired So what can we do  In view you can use the Model.propertyname(or)ViewData[“propertyname “] In  action method for post you can have model object as parameter.
Model Binders.. Validation use the Controller.Modelstate.IsValid for errors checking.  on post to a action method, Automatically Errors are added to the Modelstate Model Objects should always have error validation. Don’t depend on user post values How controls state is maintained on posts? Return the same view with model , if there is a error Model Binding tells input controls to redisplay user-entered values So always use the HTML helper classes Only basic controls are supported, you can create your own Helper methods
Data passing between view and controller
Filters Filters handovers extra framework level responsibility to Controller/Action methods Authorize: This filter is used to restrict access to a Controller or Controller action. Authorize(Roles=”Admins, SuperAdmins”)] HandleError: This filter is used to specify an action that will handle an exception that is thrown from inside an action method. [HandleError(Order=1, ExceptionType=typeof(ArgumentException), View=”ArgError”)] OutputCache: This filter is used to provide output caching for action methods. [OutputCache(Duration=60, VaryByParam=”none”)] ValidateInput: Bind: Attribute used to provide details on how model binding to a parameter should occur
Some more attributes ControllerAction attribute is option(To follow DRY Principle) ActionNameattributeallows to specify the virtual action name to the physical method name /home/view for method viewsomething() ActionSelector Attribute - an abstract base class for attributes that provide fi ne-grained control over which requests an action method can respond to. NonActionAttribute AcceptVerbs Attribute This is a concrete implementation of ActionSelectorAttribute This allows you to have two methods of the same name (with different parameters of course) both of which are actions but respond to different HTTP verbs. When a POST request for /home/edit is received, the action invoker creates a list of all methods of the Controller that match the “edit” action name.
Errors HandleError Attribute  Mark methods with this  attribute if you require to handle a special exception  [HandleError(Order=1, ExceptionType=typeof(ArgumentException), View=”ArgError”)] By default no need to mention Exception type . It returns Error view in shared folder This attribute will create and populate the System.Web.Mvc.HandleErrorInfo Error.aspx is a strongly typed view of HandleErrorInfo Enable CustomErrors in web.config How do you handle errors if the user tries to request a wrong URL?? Approach Create a controller by name Error Create a Action method with some error number /error/404 Enable custom errors and specify redirect the url to  Create a views to show the error message Retrieve the user requested url with Request.QueryString["aspxerrorpath"] Configure the Route in global.aspx(optional depends upon the existing routes) routes.MapRoute("Error“, "Error/404/{aspxerrorpath}", 			              new { controller = "Error", action = "404", aspxerrorpath = "" });
Ajax capabilities To provide asynchronous requests for Partial rendering. A separate library is provided to support Asynchronous requests 	(MicrosoftAjax.js) (MicrosoftMvcAjax.js) (Jquery.js) Only Clientside Ajax support is provided. Supported at view level Ajax Extensions are provided and are exposed with Ajax prop in a view Ajax.ActionLink() Ajax.BeginForm() At controller you can really identify the normal request and ajax request with property Request.IsAjaxRequest() x-requested-with: XMLHttpRequest Coding Rules Each AJAX routine should have dedicated Action on a Controller. The Action should check to see if the request coming in is an AJAX request. If AJAX request, Return the Content or partial view from the method if action is not an AJAX request, Each Action should return a dedicated view/ redirect to a route. Only two classes AjaxExtensions , AjaxOptions We can call web services
Clean URL Structure Friendlier to humans Friendlier to web crawlers Search engine optimization (SEO) Fits with the nature of the web MVC exposes the stateless nature of HTTP REST-like http://www.store.com/products/Books http://www.store.com/products/Books/MVC
					URL  ReWritingVs Routing 				http://www.store.com/products.aspx?category=books 				http://www.store.com/products.aspx/Books 				http://www.store.com/products/Books.aspx						http://www.store.com/products/Books Rewriting  : Rewriting is used to manipulate URL paths before the request is handled by the Web server. Page is fixed Routing:  InRouting, urls are not changed but routed to a different handler pre defined. Url is fixed
Routes A route a URL with a structure Routes are the only things exposed to the enduser (lot of abstraction) Routes are handled/resolved MVC route engine. You have to register the routes in Routescollection maintained in a RouteTable in global.aspx Routes are evaluated in order. if a route is not matched it goes to next. Routes structure have segments and can have literals other than “/”  Don’t need to give all the values for the parameters if you have defaults routes.MapRoute(“simple”, “{controller}/{action}/{id}“); site/{controller}/{action}/{id} {language}-{country}/{controller}/{action} {controller}.{action}-{id} /simple2/goodbye?name=World {controller}{action}/{id} ???????
Rules for Routes Default value position is also important Thus, default values only work when every URL parameter after the one with the default also has a default value assigned Any route parameters other than {controller} and {action} are passed as parameters to the action method, if they exist
Constraints with routes Constraints are rules on the URL segments All the constraints are regular expression compatible with class Regex routes.MapRoute(“blog”, “{year}/{month}/{day}“ , new {controller=”blog”, action=”index”} , new {year=@“{4}“, month=@“{2}“, day=@“{2}“}); Some other examples /simple2/distance?x2=1&y2=2&x1=0&y1=0 /simple2/distance/0,0/1,2 /simple2/distance/{x1},{y1}/{x2},{y2}
The Request Lifecycle
The Request Lifecycle Get  IRouteHandler Request Find the Route Get MVCRouteHandler MvcRouteHandler Get  HttpHandler from IRouteHandler MvcHandler Call   IhttpHandler. ProcessRequest() Controller RequestContext UrlRoutingModule View
Routing handlers MVCRouteHandler StopRoutingHandlerrequests resolved with this handler is ignored by mvc and handovers the request to normal HTTP Handler routes.IgnoreRoute(“{resource}.axd/{*pathInfo}“); CustomRouteHandler
Who takes the responsibility of calling a action ActionInvoker Every controller has a property ActionInvoker of type IActionInvoker, which takes the responsibility. MVC framework has ControllerActionInvokerwhich implements the interface. Routehandler will assign the instance of the ControllerActionInvokerto the controller property Main Tasks Locates the action method to call. Maps the current route data and requests data by name to the parameters of the action method. Invokes the action method and all of its filters. Calls ExecuteResult on the ActionResult returned by the action method. For methods that do not return an ActionResult, the invoker creates an implicit action result as described in the previous section and calls ExecuteResult on that.
Extensible Replace any component of the system Interface-based architecture  Very few sealed methods / classes Plays well with others Want to use NHibernate for models?  OK! Want to use Brail for views?  OK! Want to use VB for controllers?  OK! Create a custom view engine or use third-party view engines nVelocity  nhaml Spark  Brail  MVCContrib
Dry Principle examples Using validation logic in both edit and create NotFound view template across create, edit, details and delete methods Eliminate the need to explicitly specify the name when we call the View() helper method.  we are re-using the model classes for both Edit and Create action scenarios User Controls are used Changes are limited to one place
References  http://www.asp.net/mvc/ http://stephenwalther.com/blog/category/4.aspx?Show=All IIS 6, IIS7 Deployments http://www.codeproject.com/KB/aspnet/webformmvcharmony.aspx

Más contenido relacionado

La actualidad más candente

Server Controls of ASP.Net
Server Controls of ASP.NetServer Controls of ASP.Net
Server Controls of ASP.NetHitesh Santani
 
Introduction to the Web API
Introduction to the Web APIIntroduction to the Web API
Introduction to the Web APIBrad Genereaux
 
ASP.NET Web API
ASP.NET Web APIASP.NET Web API
ASP.NET Web APIhabib_786
 
Developing an ASP.NET Web Application
Developing an ASP.NET Web ApplicationDeveloping an ASP.NET Web Application
Developing an ASP.NET Web ApplicationRishi Kothari
 
Retrofit library for android
Retrofit library for androidRetrofit library for android
Retrofit library for androidInnovationM
 
Java Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and ExampleJava Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and Examplekamal kotecha
 
Page Object Model and Implementation in Selenium
Page Object Model and Implementation in Selenium  Page Object Model and Implementation in Selenium
Page Object Model and Implementation in Selenium Zoe Gilbert
 
What is Dependency Injection in Spring Boot | Edureka
What is Dependency Injection in Spring Boot | EdurekaWhat is Dependency Injection in Spring Boot | Edureka
What is Dependency Injection in Spring Boot | EdurekaEdureka!
 
Asp Net Advance Topics
Asp Net Advance TopicsAsp Net Advance Topics
Asp Net Advance TopicsAli Taki
 

La actualidad más candente (20)

Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
 
Server Controls of ASP.Net
Server Controls of ASP.NetServer Controls of ASP.Net
Server Controls of ASP.Net
 
Introduction to the Web API
Introduction to the Web APIIntroduction to the Web API
Introduction to the Web API
 
ASP.NET Web API
ASP.NET Web APIASP.NET Web API
ASP.NET Web API
 
Mvc architecture
Mvc architectureMvc architecture
Mvc architecture
 
Developing an ASP.NET Web Application
Developing an ASP.NET Web ApplicationDeveloping an ASP.NET Web Application
Developing an ASP.NET Web Application
 
Web forms in ASP.net
Web forms in ASP.netWeb forms in ASP.net
Web forms in ASP.net
 
Selenium introduction
Selenium introductionSelenium introduction
Selenium introduction
 
Spring boot
Spring bootSpring boot
Spring boot
 
Spring Security 5
Spring Security 5Spring Security 5
Spring Security 5
 
Retrofit library for android
Retrofit library for androidRetrofit library for android
Retrofit library for android
 
Java Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and ExampleJava Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and Example
 
Page Object Model and Implementation in Selenium
Page Object Model and Implementation in Selenium  Page Object Model and Implementation in Selenium
Page Object Model and Implementation in Selenium
 
What is Dependency Injection in Spring Boot | Edureka
What is Dependency Injection in Spring Boot | EdurekaWhat is Dependency Injection in Spring Boot | Edureka
What is Dependency Injection in Spring Boot | Edureka
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
 
Asp Net Advance Topics
Asp Net Advance TopicsAsp Net Advance Topics
Asp Net Advance Topics
 
Spring MVC
Spring MVCSpring MVC
Spring MVC
 
Introduction to es6
Introduction to es6Introduction to es6
Introduction to es6
 
Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScript
 
JavaScript JQUERY AJAX
JavaScript JQUERY AJAXJavaScript JQUERY AJAX
JavaScript JQUERY AJAX
 

Destacado

Python mu Java mı?
Python mu Java mı?Python mu Java mı?
Python mu Java mı?aerkanc
 
Ruby - Dünyanın En Güzel Programlama Dili
Ruby - Dünyanın En Güzel Programlama DiliRuby - Dünyanın En Güzel Programlama Dili
Ruby - Dünyanın En Güzel Programlama DiliSerdar Dogruyol
 
Ruby Programlama Dili
Ruby Programlama DiliRuby Programlama Dili
Ruby Programlama Dilipinguar
 
Introduction to C# 6.0 and 7.0
Introduction to C# 6.0 and 7.0Introduction to C# 6.0 and 7.0
Introduction to C# 6.0 and 7.0Saineshwar bageri
 
C# 3.0 and 4.0
C# 3.0 and 4.0C# 3.0 and 4.0
C# 3.0 and 4.0Buu Nguyen
 
Native i os, android, and windows development in c# with xamarin 4
Native i os, android, and windows development in c# with xamarin 4Native i os, android, and windows development in c# with xamarin 4
Native i os, android, and windows development in c# with xamarin 4Xamarin
 

Destacado (6)

Python mu Java mı?
Python mu Java mı?Python mu Java mı?
Python mu Java mı?
 
Ruby - Dünyanın En Güzel Programlama Dili
Ruby - Dünyanın En Güzel Programlama DiliRuby - Dünyanın En Güzel Programlama Dili
Ruby - Dünyanın En Güzel Programlama Dili
 
Ruby Programlama Dili
Ruby Programlama DiliRuby Programlama Dili
Ruby Programlama Dili
 
Introduction to C# 6.0 and 7.0
Introduction to C# 6.0 and 7.0Introduction to C# 6.0 and 7.0
Introduction to C# 6.0 and 7.0
 
C# 3.0 and 4.0
C# 3.0 and 4.0C# 3.0 and 4.0
C# 3.0 and 4.0
 
Native i os, android, and windows development in c# with xamarin 4
Native i os, android, and windows development in c# with xamarin 4Native i os, android, and windows development in c# with xamarin 4
Native i os, android, and windows development in c# with xamarin 4
 

Similar a ASP.MVC Training

ASP.NET MVC controllers
ASP.NET MVC controllersASP.NET MVC controllers
ASP.NET MVC controllersMahmoud Tolba
 
Introduction To Mvc
Introduction To MvcIntroduction To Mvc
Introduction To MvcVolkan Uzun
 
MVC ppt presentation
MVC ppt presentationMVC ppt presentation
MVC ppt presentationBhavin Shah
 
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 4 [Part - 2]
ASP.Net MVC 4 [Part - 2]ASP.Net MVC 4 [Part - 2]
ASP.Net MVC 4 [Part - 2]Mohamed Abdeen
 
.NET Core, ASP.NET Core Course, Session 9
.NET Core, ASP.NET Core Course, Session 9.NET Core, ASP.NET Core Course, Session 9
.NET Core, ASP.NET Core Course, Session 9aminmesbahi
 
Simple mvc4 prepared by gigin krishnan
Simple mvc4 prepared by gigin krishnanSimple mvc4 prepared by gigin krishnan
Simple mvc4 prepared by gigin krishnanGigin Krishnan
 
SoftServe - "ASP.NET MVC як наступний крок у розвитку технології розробки Web...
SoftServe - "ASP.NET MVC як наступний крок у розвитку технології розробки Web...SoftServe - "ASP.NET MVC як наступний крок у розвитку технології розробки Web...
SoftServe - "ASP.NET MVC як наступний крок у розвитку технології розробки Web...SoftServe
 
Introduction to Angularjs : kishan kumar
Introduction to Angularjs : kishan kumarIntroduction to Angularjs : kishan kumar
Introduction to Angularjs : kishan kumarAppfinz Technologies
 
Mvvm in the real world tccc10
Mvvm in the real world   tccc10Mvvm in the real world   tccc10
Mvvm in the real world tccc10Bryan Anderson
 
CTTDNUG ASP.NET MVC
CTTDNUG ASP.NET MVCCTTDNUG ASP.NET MVC
CTTDNUG ASP.NET MVCBarry Gervin
 

Similar a ASP.MVC Training (20)

MVC 4
MVC 4MVC 4
MVC 4
 
ASP.NET MVC controllers
ASP.NET MVC controllersASP.NET MVC controllers
ASP.NET MVC controllers
 
Asp.Net MVC Intro
Asp.Net MVC IntroAsp.Net MVC Intro
Asp.Net MVC Intro
 
Introduction To Mvc
Introduction To MvcIntroduction To Mvc
Introduction To Mvc
 
Asp.net mvc
Asp.net mvcAsp.net mvc
Asp.net mvc
 
MVC Training Part 1
MVC Training Part 1MVC Training Part 1
MVC Training Part 1
 
MVC ppt presentation
MVC ppt presentationMVC ppt presentation
MVC ppt presentation
 
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
Asp.net,mvcAsp.net,mvc
Asp.net,mvc
 
ASP.Net MVC 4 [Part - 2]
ASP.Net MVC 4 [Part - 2]ASP.Net MVC 4 [Part - 2]
ASP.Net MVC 4 [Part - 2]
 
.NET Core, ASP.NET Core Course, Session 9
.NET Core, ASP.NET Core Course, Session 9.NET Core, ASP.NET Core Course, Session 9
.NET Core, ASP.NET Core Course, Session 9
 
MVC Training Part 2
MVC Training Part 2MVC Training Part 2
MVC Training Part 2
 
Chapter4.pptx
Chapter4.pptxChapter4.pptx
Chapter4.pptx
 
Simple mvc4 prepared by gigin krishnan
Simple mvc4 prepared by gigin krishnanSimple mvc4 prepared by gigin krishnan
Simple mvc4 prepared by gigin krishnan
 
SoftServe - "ASP.NET MVC як наступний крок у розвитку технології розробки Web...
SoftServe - "ASP.NET MVC як наступний крок у розвитку технології розробки Web...SoftServe - "ASP.NET MVC як наступний крок у розвитку технології розробки Web...
SoftServe - "ASP.NET MVC як наступний крок у розвитку технології розробки Web...
 
Jinal desai .net
Jinal desai .netJinal desai .net
Jinal desai .net
 
Introduction to Angularjs : kishan kumar
Introduction to Angularjs : kishan kumarIntroduction to Angularjs : kishan kumar
Introduction to Angularjs : kishan kumar
 
Introduction to Angularjs
Introduction to AngularjsIntroduction to Angularjs
Introduction to Angularjs
 
Mvvm in the real world tccc10
Mvvm in the real world   tccc10Mvvm in the real world   tccc10
Mvvm in the real world tccc10
 
CTTDNUG ASP.NET MVC
CTTDNUG ASP.NET MVCCTTDNUG ASP.NET MVC
CTTDNUG ASP.NET MVC
 

Último

Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
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
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
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
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
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
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
[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
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 

Último (20)

Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
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
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
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...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
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
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
[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
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 

ASP.MVC Training

  • 1. ASP.NET MVC Mahesh Sikakolli
  • 2. MVC Pattern A architectural design pattern used in software engineering Acronym for Model ● View ● Controller Often seen in web applications but not limited to it Def Isolate the business logic from input and presentation, permitting independent development, testing and maintenance of each. Separation of concerns
  • 4. WebForms are great … WebForms are great … Mature, proven technology Scalable Extensible Familiar feel to WinForms developers Lot of features like viewstate , rich controls support, page life cycle … but they have challenges Abstractions aren’t very abstract Difficult to test Lack of control over markup It does things you didn’t tell it to do Slow because of controls and page cycles
  • 5. ASP.NET MVC Framework Goals Utilize ASP.NET architecture. Testability Loosely Coupled and extensible Tight control over markup User/SEO friendly URLs Adopt REST concepts Leverage the benefits of ASP.NET Separation of concerns SRP – Single Responsibility Principle DRY – Don’t Repeat Yourself -Changes are limited to one place Helps with concurrent development Convention over configuration
  • 6. What happend to Webforms Not a replacement for WebForms All about alternatives Fundamental Part of the System.Web namespace Same team that builds WebForms Providers still work Membership, Caching, Session, etc. Views leverage .aspx and .ascx But they don’t have to if you don’t want them to Feature Sharing
  • 7. What is ASP.NET MVC? Controller Request Step 1 Incoming request directed to Controller
  • 8. Model What is ASP.NET MVC? Controller Step 2 Controller processes request and forms a data Model
  • 9. View What is ASP.NET MVC? Controller View Step 3 Model is passed to View
  • 10. View What is ASP.NET MVC? Controller View Step 4 View transforms Model into appropriate output format
  • 11. What is ASP.NET MVC? Controller View Response Step 5 Response is rendered
  • 12. ModelVC Model represents the business objects, the data of the application. Apart from giving the data objects, it doesn’t have significance in the framework You can use any of the following technologies to build model objects LINQ to Entities, LINQ to SQL, NHibernate, LLBLGen Pro, SubSonic, WilsonORM just raw ADO.NET DataReaders or DataSets.
  • 13. MVController Controller is the core component in MVC which intercepts and process the requests with the help of views and models Every controller has one or more Action methods. All requests are mapped to a public methods in a controller are called Actions Controller and its Action methods not exposed to outside, but mapped with corresponding routes. A controller is a class extended from abstract System.Web.Mvc.Controller or Icontroller. All the controllers should be available in a folder by name controllers. Controller naming standard should be “nameController” Routing handler will look for the named controller in routing collection and handovers the request to the controller/action. Every controller has ControllerContext(RequestContext+HttpContext) Every controller has virtual methods which can be override OnActionExecuted, OnAuthorization, OnException, OnResultExecuting
  • 14. MViewC Views are the end user interface elements/Html templates of the application. View pages are not exposed outside. Views are returned from Action methods using overload view methods of controller Return View(); return View(“NotIndex”); return View(“~/Some/Other/View.aspx”); View(products) View and controller share the date with viewData Views page are extended from ASP.NET Page object. Can have server code with <% %> and client side code. Two types of views StronglyTyped Model object is available to access strongly typed object Inherits from System.Web.Mvc.ViewPage<Model> Generic view ViewData object is available to access ViewDataDictionary Inherits from System.Web.Mvc.ViewPage Generally views are available in “viewsontrollername” folder Views supports usercontrols and masterpages. WebFormViewEngine Can I use both model and viewdata same time?s
  • 15. Action method Typically Action method will communicate with business logic tire and get the actual data to be rendered. Every public method in a Controller is a Action method. By default every action method is mapped to the view with same name in the viewsontroller folder. Method can contain parameters, Parameters are passed by the urls (or) generic View (or) Model Binders incase of strongly typed views /Products/List/car (or) /Products/List?name=car Every method will return a instance of abstract class ActionResultor a derived class Not every methods members are Action methods If a method is with NonActionAttribute Special methods such as constructors, property assessors, and event assessors cannot be action methods. Methods originally defined on Object (such as ToString)
  • 16. ActionResult Every method will return a class that derived from ActionResult abstract base class ActionResultwill handle framework level work (where as Action methods will handle application logic) Lot of helper methods are available in controller for returning ActionResult instances You can also instantiate and return a ActionResult .new ViewResult {ViewData = this.ViewData }; Its not compulsory to return a ActionResult. But you can return the string datatype. But it uses the ContentResult to return the actual data by converting to a string datatype. You can create your own ActionResult public abstract class ActionResult { public abstract void ExecuteResult(ControllerContext context); }
  • 18. HTML Helper methods Set of methods which helps to generate the basic html. They works with Routing Engine and MVC Features(like validation) There are times when you don’t want to be in control over the markup. All defined in System.Web.Mvc.Html. Extension methods are in HtmlHelper class HtmlHelper class which is exposed by Viewpage.HTML() Set of common patters All helpers attribute encode attribute values. Automatic binding of values with the values in the ModelStatedictionary. The name argument to the helper is used as the key to the dictionary. If the ModelStatecontains an error, the form helper associated with that error will render a CSS class of “input-validation-error” in addition to any explicitly specified CSS classes. Different types of HTML Helpers are available(check in object Browser) Also supports rendering partial views(user controls)
  • 19. Validation You find the errors in the controller, how do you propagate them to the view? The answer is System.Web.Mvc.ModelStateDictionary ,ModelState Process You have to add all error messages to ModelstateDictionary in Action method Html.ValidationMessage(“name”) Html.ValidationMessage(“Key” , ”Custom Error Message”) class=” field-validation-error” is used to show the message Html.ValidationSummary(“custom message”) Displays unordered list of all validation errors in the ModelState dictionary class=”validation-summary-errors” is used to format which is available in template Do not confuse the Model(ViewDataDictionary) object in a view with ModelState(ModelStateDictionary) in a controller The default model binder supports the use of objects that implement ComponentModels.IDataErrorInfo
  • 20. Model Binders These are user defined classes Used to define the strongly typed views of model objects To make easy of handling HTTP Post requests and helps in populating the parameters in action methods. Models are passed between Action method Strongly Typed Views Use attribute to override model binding Bind(Exclude:="Id") How? Incoming data is automatically parsed and used to populate action method parameters by matching incoming key/value pairs of the http request with the names of properties on the desired So what can we do In view you can use the Model.propertyname(or)ViewData[“propertyname “] In action method for post you can have model object as parameter.
  • 21. Model Binders.. Validation use the Controller.Modelstate.IsValid for errors checking. on post to a action method, Automatically Errors are added to the Modelstate Model Objects should always have error validation. Don’t depend on user post values How controls state is maintained on posts? Return the same view with model , if there is a error Model Binding tells input controls to redisplay user-entered values So always use the HTML helper classes Only basic controls are supported, you can create your own Helper methods
  • 22. Data passing between view and controller
  • 23. Filters Filters handovers extra framework level responsibility to Controller/Action methods Authorize: This filter is used to restrict access to a Controller or Controller action. Authorize(Roles=”Admins, SuperAdmins”)] HandleError: This filter is used to specify an action that will handle an exception that is thrown from inside an action method. [HandleError(Order=1, ExceptionType=typeof(ArgumentException), View=”ArgError”)] OutputCache: This filter is used to provide output caching for action methods. [OutputCache(Duration=60, VaryByParam=”none”)] ValidateInput: Bind: Attribute used to provide details on how model binding to a parameter should occur
  • 24. Some more attributes ControllerAction attribute is option(To follow DRY Principle) ActionNameattributeallows to specify the virtual action name to the physical method name /home/view for method viewsomething() ActionSelector Attribute - an abstract base class for attributes that provide fi ne-grained control over which requests an action method can respond to. NonActionAttribute AcceptVerbs Attribute This is a concrete implementation of ActionSelectorAttribute This allows you to have two methods of the same name (with different parameters of course) both of which are actions but respond to different HTTP verbs. When a POST request for /home/edit is received, the action invoker creates a list of all methods of the Controller that match the “edit” action name.
  • 25. Errors HandleError Attribute Mark methods with this attribute if you require to handle a special exception [HandleError(Order=1, ExceptionType=typeof(ArgumentException), View=”ArgError”)] By default no need to mention Exception type . It returns Error view in shared folder This attribute will create and populate the System.Web.Mvc.HandleErrorInfo Error.aspx is a strongly typed view of HandleErrorInfo Enable CustomErrors in web.config How do you handle errors if the user tries to request a wrong URL?? Approach Create a controller by name Error Create a Action method with some error number /error/404 Enable custom errors and specify redirect the url to Create a views to show the error message Retrieve the user requested url with Request.QueryString["aspxerrorpath"] Configure the Route in global.aspx(optional depends upon the existing routes) routes.MapRoute("Error“, "Error/404/{aspxerrorpath}", new { controller = "Error", action = "404", aspxerrorpath = "" });
  • 26. Ajax capabilities To provide asynchronous requests for Partial rendering. A separate library is provided to support Asynchronous requests (MicrosoftAjax.js) (MicrosoftMvcAjax.js) (Jquery.js) Only Clientside Ajax support is provided. Supported at view level Ajax Extensions are provided and are exposed with Ajax prop in a view Ajax.ActionLink() Ajax.BeginForm() At controller you can really identify the normal request and ajax request with property Request.IsAjaxRequest() x-requested-with: XMLHttpRequest Coding Rules Each AJAX routine should have dedicated Action on a Controller. The Action should check to see if the request coming in is an AJAX request. If AJAX request, Return the Content or partial view from the method if action is not an AJAX request, Each Action should return a dedicated view/ redirect to a route. Only two classes AjaxExtensions , AjaxOptions We can call web services
  • 27. Clean URL Structure Friendlier to humans Friendlier to web crawlers Search engine optimization (SEO) Fits with the nature of the web MVC exposes the stateless nature of HTTP REST-like http://www.store.com/products/Books http://www.store.com/products/Books/MVC
  • 28. URL ReWritingVs Routing http://www.store.com/products.aspx?category=books http://www.store.com/products.aspx/Books http://www.store.com/products/Books.aspx http://www.store.com/products/Books Rewriting : Rewriting is used to manipulate URL paths before the request is handled by the Web server. Page is fixed Routing: InRouting, urls are not changed but routed to a different handler pre defined. Url is fixed
  • 29. Routes A route a URL with a structure Routes are the only things exposed to the enduser (lot of abstraction) Routes are handled/resolved MVC route engine. You have to register the routes in Routescollection maintained in a RouteTable in global.aspx Routes are evaluated in order. if a route is not matched it goes to next. Routes structure have segments and can have literals other than “/” Don’t need to give all the values for the parameters if you have defaults routes.MapRoute(“simple”, “{controller}/{action}/{id}“); site/{controller}/{action}/{id} {language}-{country}/{controller}/{action} {controller}.{action}-{id} /simple2/goodbye?name=World {controller}{action}/{id} ???????
  • 30. Rules for Routes Default value position is also important Thus, default values only work when every URL parameter after the one with the default also has a default value assigned Any route parameters other than {controller} and {action} are passed as parameters to the action method, if they exist
  • 31. Constraints with routes Constraints are rules on the URL segments All the constraints are regular expression compatible with class Regex routes.MapRoute(“blog”, “{year}/{month}/{day}“ , new {controller=”blog”, action=”index”} , new {year=@“{4}“, month=@“{2}“, day=@“{2}“}); Some other examples /simple2/distance?x2=1&y2=2&x1=0&y1=0 /simple2/distance/0,0/1,2 /simple2/distance/{x1},{y1}/{x2},{y2}
  • 33. The Request Lifecycle Get IRouteHandler Request Find the Route Get MVCRouteHandler MvcRouteHandler Get HttpHandler from IRouteHandler MvcHandler Call IhttpHandler. ProcessRequest() Controller RequestContext UrlRoutingModule View
  • 34. Routing handlers MVCRouteHandler StopRoutingHandlerrequests resolved with this handler is ignored by mvc and handovers the request to normal HTTP Handler routes.IgnoreRoute(“{resource}.axd/{*pathInfo}“); CustomRouteHandler
  • 35. Who takes the responsibility of calling a action ActionInvoker Every controller has a property ActionInvoker of type IActionInvoker, which takes the responsibility. MVC framework has ControllerActionInvokerwhich implements the interface. Routehandler will assign the instance of the ControllerActionInvokerto the controller property Main Tasks Locates the action method to call. Maps the current route data and requests data by name to the parameters of the action method. Invokes the action method and all of its filters. Calls ExecuteResult on the ActionResult returned by the action method. For methods that do not return an ActionResult, the invoker creates an implicit action result as described in the previous section and calls ExecuteResult on that.
  • 36. Extensible Replace any component of the system Interface-based architecture Very few sealed methods / classes Plays well with others Want to use NHibernate for models? OK! Want to use Brail for views? OK! Want to use VB for controllers? OK! Create a custom view engine or use third-party view engines nVelocity  nhaml Spark  Brail  MVCContrib
  • 37. Dry Principle examples Using validation logic in both edit and create NotFound view template across create, edit, details and delete methods Eliminate the need to explicitly specify the name when we call the View() helper method.  we are re-using the model classes for both Edit and Create action scenarios User Controls are used Changes are limited to one place
  • 38. References http://www.asp.net/mvc/ http://stephenwalther.com/blog/category/4.aspx?Show=All IIS 6, IIS7 Deployments http://www.codeproject.com/KB/aspnet/webformmvcharmony.aspx