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

Weitere ähnliche Inhalte

Was ist angesagt?

Introduction to ReactJS
Introduction to ReactJSIntroduction to ReactJS
Introduction to ReactJSHoang Long
 
ReactJS presentation
ReactJS presentationReactJS presentation
ReactJS presentationThanh Tuong
 
Chapitre 2-Data binding.pdf
Chapitre 2-Data binding.pdfChapitre 2-Data binding.pdf
Chapitre 2-Data binding.pdfBoubakerMedanas
 
Introduction to the Web API
Introduction to the Web APIIntroduction to the Web API
Introduction to the Web APIBrad Genereaux
 
Introduction to React JS for beginners
Introduction to React JS for beginners Introduction to React JS for beginners
Introduction to React JS for beginners Varun Raj
 
Asp.net mvc basic introduction
Asp.net mvc basic introductionAsp.net mvc basic introduction
Asp.net mvc basic introductionBhagath Gopinath
 
Asp.net MVC training session
Asp.net MVC training sessionAsp.net MVC training session
Asp.net MVC training sessionHrichi Mohamed
 
ASP.NET Presentation
ASP.NET PresentationASP.NET Presentation
ASP.NET Presentationdimuthu22
 
introduction to Vue.js 3
introduction to Vue.js 3 introduction to Vue.js 3
introduction to Vue.js 3 ArezooKmn
 
learn what React JS is & why we should use React JS .
learn what React JS is & why we should use React JS .learn what React JS is & why we should use React JS .
learn what React JS is & why we should use React JS .paradisetechsoftsolutions
 
ASP.NET MVC 3.0 Validation
ASP.NET MVC 3.0 ValidationASP.NET MVC 3.0 Validation
ASP.NET MVC 3.0 ValidationEyal Vardi
 

Was ist angesagt? (20)

Introduction to ReactJS
Introduction to ReactJSIntroduction to ReactJS
Introduction to ReactJS
 
Les Servlets et JSP
Les Servlets et JSPLes Servlets et JSP
Les Servlets et JSP
 
Spring MVC
Spring MVCSpring MVC
Spring MVC
 
Intro to React
Intro to ReactIntro to React
Intro to React
 
ReactJS presentation
ReactJS presentationReactJS presentation
ReactJS presentation
 
Chapitre 2-Data binding.pdf
Chapitre 2-Data binding.pdfChapitre 2-Data binding.pdf
Chapitre 2-Data binding.pdf
 
Introduction to the Web API
Introduction to the Web APIIntroduction to the Web API
Introduction to the Web API
 
Introduction to React JS for beginners
Introduction to React JS for beginners Introduction to React JS for beginners
Introduction to React JS for beginners
 
VueJS: The Simple Revolution
VueJS: The Simple RevolutionVueJS: The Simple Revolution
VueJS: The Simple Revolution
 
Intro to React
Intro to ReactIntro to React
Intro to React
 
Asp.net mvc basic introduction
Asp.net mvc basic introductionAsp.net mvc basic introduction
Asp.net mvc basic introduction
 
Spring mvc
Spring mvcSpring mvc
Spring mvc
 
Asp.net MVC training session
Asp.net MVC training sessionAsp.net MVC training session
Asp.net MVC training session
 
ASP.NET Presentation
ASP.NET PresentationASP.NET Presentation
ASP.NET Presentation
 
JPA Best Practices
JPA Best PracticesJPA Best Practices
JPA Best Practices
 
React hooks
React hooksReact hooks
React hooks
 
introduction to Vue.js 3
introduction to Vue.js 3 introduction to Vue.js 3
introduction to Vue.js 3
 
learn what React JS is & why we should use React JS .
learn what React JS is & why we should use React JS .learn what React JS is & why we should use React JS .
learn what React JS is & why we should use React JS .
 
ASP.NET MVC 3.0 Validation
ASP.NET MVC 3.0 ValidationASP.NET MVC 3.0 Validation
ASP.NET MVC 3.0 Validation
 
Soap vs rest
Soap vs restSoap vs rest
Soap vs rest
 

Andere mochten auch

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
 

Andere mochten auch (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
 

Ähnlich wie 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
 

Ähnlich wie 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
 

Kürzlich hochgeladen

Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
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
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
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
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
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
 
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
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
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
 
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
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 

Kürzlich hochgeladen (20)

Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
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
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
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
 
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...
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
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
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 

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