SlideShare a Scribd company logo
ASP.NET MVC Mahesh Sikakolli
MVC PatternA architectural design pattern used in software engineeringAcronym for Model ● View ● ControllerOften seen in web applications but not limited to itDefIsolate 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 technologyScalableExtensibleFamiliar feel to WinForms developersLot of features like viewstate , rich controls support, page life cycle… but they have challengesAbstractions aren’t very abstractDifficult to testLack of control over markupIt does things you didn’t tell it to doSlow because of controls and page cycles
ASP.NET MVC Framework GoalsUtilize ASP.NET architecture.Testability Loosely Coupled and extensibleTight control over markupUser/SEO friendly URLsAdopt REST conceptsLeverage the benefits of ASP.NETSeparation of concernsSRP – Single Responsibility PrincipleDRY – Don’t Repeat Yourself  -Changes are limited to one placeHelps with concurrent developmentConvention over configuration
What happend to WebformsNot a replacement for WebFormsAll about alternativesFundamentalPart of the System.Web namespaceSame team that builds WebFormsProviders still workMembership, Caching, Session, etc.Views leverage .aspx and .ascxBut they don’t have to if you don’t want them toFeature Sharing
What is ASP.NET MVC?ControllerRequestStep 1Incoming request directed to Controller
ModelWhat is ASP.NET MVC?ControllerStep 2Controller processes request and forms a data Model
ViewWhat is ASP.NET MVC?ControllerViewStep 3Model is passed to View
ViewWhat is ASP.NET MVC?ControllerViewStep 4View transforms Model into appropriate output format
What is ASP.NET MVC?ControllerViewResponseStep 5Response is rendered
ModelVCModel represents the business objects, the data of the application.Apart from giving the data objects, it doesn’t have significance in the frameworkYou can use any of the following technologies to  build model objectsLINQ to Entities, LINQ to SQL,NHibernate, LLBLGen Pro, SubSonic, WilsonORMjust raw ADO.NET DataReaders or DataSets.
MVControllerController is the core component in MVC  which intercepts and process the requests with the help of views and modelsEvery controller has one or more Action methods.All requests are mapped to a public methods in a controller are called ActionsController 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
MViewCViews 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 viewDataViews page are extended from ASP.NET Page object.Can have server code with <% %> and client side code.Two types of viewsStronglyTypedModel object is available to access  strongly typed object Inherits from  System.Web.Mvc.ViewPage<Model>Generic view ViewData object is available to access  ViewDataDictionaryInherits from System.Web.Mvc.ViewPageGenerally views are available in “views\Controllername” folder Views supports usercontrols and masterpages.WebFormViewEngineCan I use both model and viewdata same time?s
Action methodTypically 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 views\Controller 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=carEvery method will return a instance of abstract class ActionResultor a derived classNot every methods members are Action methodsIf a method is with NonActionAttributeSpecial methods such as constructors, property assessors, and event assessors cannot be action methods.Methods originally defined on Object (such as ToString)
ActionResultEvery method will return a class that derived from ActionResult abstract base classActionResultwill handle framework level work (where as Action methods will handle application logic)Lot of helper methods are available in controller  for returning ActionResult instancesYou 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 ActionResultpublic abstract class ActionResult{		public abstract void ExecuteResult(ControllerContext context);}
ActionResult Types
HTML Helper methodsSet 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 pattersAll 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)
ValidationYou find the errors in the controller, how do you propagate them to the view?The answer is System.Web.Mvc.ModelStateDictionary ,ModelStateProcessYou have to add all error messages to ModelstateDictionary in Action methodHtml.ValidationMessage(“name”)Html.ValidationMessage(“Key” ,  ”Custom Error Message”)class=” field-validation-error” is used to show the messageHtml.ValidationSummary(“custom message”)Displays unordered list of all validation errors in the ModelState dictionaryclass=”validation-summary-errors” is used to format which is available in templateDo 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 BindersThese are user defined classes Used to define the strongly typed views of model objectsTo make easy of handling HTTP Post requests and helps in populating the parameters in action methods.Models are passed betweenAction method Strongly Typed ViewsUse 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 desiredSo 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..Validationuse the Controller.Modelstate.IsValid for errors checking. on post to a action method, Automatically Errors are added to the ModelstateModel Objects should always have error validation. Don’t depend on user post valuesHow controls state is maintained on posts?Return the same view with model , if there is a errorModel Binding tells input controls to redisplay user-entered valuesSo always use the HTML helper classesOnly basic controls are supported, you can create your own Helper methods
Data passing between view and controller
FiltersFilters handovers extra framework level responsibility to Controller/Action methodsAuthorize: 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 attributesControllerAction 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.NonActionAttributeAcceptVerbs AttributeThis is a concrete implementation of ActionSelectorAttributeThis 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.
ErrorsHandleError 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 folderThis attribute will create and populate the System.Web.Mvc.HandleErrorInfoError.aspx is a strongly typed view of HandleErrorInfoEnable CustomErrors in web.configHow do you handle errors if the user tries to request a wrong URL??ApproachCreate a controller by name ErrorCreate a Action method with some error number/error/404Enable custom errors and specify redirect the url to Create a views to show the error messageRetrieve 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 capabilitiesTo 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 levelAjax Extensions are provided and are exposed with Ajax prop in a viewAjax.ActionLink()Ajax.BeginForm()At controller you can really identify the normal request and ajax request with property Request.IsAjaxRequest()x-requested-with: XMLHttpRequestCoding RulesEach 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 methodif action is not an AJAX request, Each Action should return a dedicated view/ redirect to a route.Only two classes AjaxExtensions , AjaxOptionsWe can call web services
Clean URL StructureFriendlier to humansFriendlier to web crawlersSearch engine optimization (SEO)Fits with the nature of the webMVC exposes the stateless nature of HTTPREST-likehttp://www.store.com/products/Bookshttp://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/BooksRewriting  : Rewriting is used to manipulate URL paths before the request is handled by the Web server. Page is fixedRouting:  InRouting, urls are not changed but routed to a different handler pre defined. Url is fixed
RoutesA route a URL with a structureRoutes 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.aspxRoutes 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 defaultsroutes.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 RoutesDefault value position is also importantThus, default values only work when every URL parameter after the one with the default also has a default value assignedAny route parameters other than {controller} and {action} are passed as parameters to the action method, if they exist
Constraints with routesConstraints are rules on the URL segmentsAll the constraints are regular expression compatible with class Regexroutes.MapRoute(“blog”, “{year}/{month}/{day}“, new {controller=”blog”, action=”index”} , new {year=@“\d{4}“, month=@“\d{2}“, day=@“\d{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 LifecycleGet  IRouteHandlerRequestFind the RouteGet MVCRouteHandlerMvcRouteHandlerGet HttpHandler from IRouteHandlerMvcHandlerCall  IhttpHandler. ProcessRequest()ControllerRequestContextUrlRoutingModuleView
Routing handlersMVCRouteHandlerStopRoutingHandlerrequests resolved with this handler is ignored by mvc and handovers the request to normal HTTP Handlerroutes.IgnoreRoute(“{resource}.axd/{*pathInfo}“);CustomRouteHandler
Who takes the responsibility of calling a actionActionInvokerEvery 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 propertyMain TasksLocates 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.
ExtensibleReplace any component of the systemInterface-based architecture Very few sealed methods / classesPlays well with othersWant 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 enginesnVelocity nhamlSpark Brail MVCContrib
Dry Principle examplesUsing validation logic in both edit and createNotFound view template across create, edit, details and delete methodsEliminate 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 scenariosUser Controls are usedChanges are limited to one place
References http://www.asp.net/mvc/http://stephenwalther.com/blog/category/4.aspx?Show=AllIIS 6, IIS7 Deploymentshttp://www.codeproject.com/KB/aspnet/webformmvcharmony.aspx

More Related Content

PDF
MVC architecture
PPTX
Introduction to mvc architecture
PPTX
Asp.net MVC training session
PPTX
PPTX
Model view controller (mvc)
PPTX
ASP.NET MVC.
 
PPTX
Collections in-csharp
PDF
Model View Controller (MVC)
MVC architecture
Introduction to mvc architecture
Asp.net MVC training session
Model view controller (mvc)
ASP.NET MVC.
 
Collections in-csharp
Model View Controller (MVC)

What's hot (20)

PPTX
HTML/CSS/java Script/Jquery
PPTX
React hooks
PPTX
jQuery PPT
PPTX
Software Architecture and Design
PPTX
Implicit objects advance Java
PDF
WEB DEVELOPMENT USING REACT JS
PPTX
Angularjs PPT
PPTX
MVVM ( Model View ViewModel )
PPT
Angular 8
PPT
MVC ppt presentation
PPT
Asp.net basic
PPT
Oops concept in c#
PPTX
Data models
PPT
React js
PPTX
Ajax and Jquery
PPTX
Laravel Tutorial PPT
PPT
ASP.NET MVC Presentation
PDF
MySQL for beginners
HTML/CSS/java Script/Jquery
React hooks
jQuery PPT
Software Architecture and Design
Implicit objects advance Java
WEB DEVELOPMENT USING REACT JS
Angularjs PPT
MVVM ( Model View ViewModel )
Angular 8
MVC ppt presentation
Asp.net basic
Oops concept in c#
Data models
React js
Ajax and Jquery
Laravel Tutorial PPT
ASP.NET MVC Presentation
MySQL for beginners
Ad

Viewers also liked (6)

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

Similar to ASP.MVC Training (20)

PDF
ASP.NET MVC 2.0
PPTX
Chapter4.pptx
PPTX
Asp.net mvc
PPTX
Asp.Net MVC Intro
PPTX
Asp.net mvc training
PPTX
Asp.NET MVC
PPTX
Asp.net mvc presentation by Nitin Sawant
PPTX
Introduction to ASP.Net MVC
PPTX
Asp.Net MVC 5 in Arabic
PPS
Introduction To Mvc
PDF
Applying Domain Driven Design on Asp.net MVC – Part 1: Asp.net MVC
PDF
Asp.Net MVC Framework Design Pattern
PPT
ASP.NET-MVC-Part-1.ppt
PPTX
Hanselman lipton asp_connections_ams304_mvc
PPTX
MVC Training Part 1
PDF
Mvc interview questions – deep dive jinal desai
PPTX
Getting started with MVC 5 and Visual Studio 2013
PDF
Jinal desai .net
PPT
ASP .net MVC
PPT
CTTDNUG ASP.NET MVC
ASP.NET MVC 2.0
Chapter4.pptx
Asp.net mvc
Asp.Net MVC Intro
Asp.net mvc training
Asp.NET MVC
Asp.net mvc presentation by Nitin Sawant
Introduction to ASP.Net MVC
Asp.Net MVC 5 in Arabic
Introduction To Mvc
Applying Domain Driven Design on Asp.net MVC – Part 1: Asp.net MVC
Asp.Net MVC Framework Design Pattern
ASP.NET-MVC-Part-1.ppt
Hanselman lipton asp_connections_ams304_mvc
MVC Training Part 1
Mvc interview questions – deep dive jinal desai
Getting started with MVC 5 and Visual Studio 2013
Jinal desai .net
ASP .net MVC
CTTDNUG ASP.NET MVC

Recently uploaded (20)

PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
KodekX | Application Modernization Development
PPTX
Web Security: Login Bypass, SQLi, CSRF & XSS.pptx
PDF
Dell Pro 14 Plus: Be better prepared for what’s coming
PDF
Chapter 2 Digital Image Fundamentals.pdf
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Top Generative AI Tools for Patent Drafting in 2025.pdf
PDF
A Day in the Life of Location Data - Turning Where into How.pdf
PPTX
ABU RAUP TUGAS TIK kelas 8 hjhgjhgg.pptx
PDF
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
PPTX
Belt and Road Supply Chain Finance Blockchain Solution
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
CIFDAQ's Teaching Thursday: Moving Averages Made Simple
PDF
DevOps & Developer Experience Summer BBQ
PDF
CIFDAQ's Market Wrap: Ethereum Leads, Bitcoin Lags, Institutions Shift
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PDF
Google’s NotebookLM Unveils Video Overviews
PDF
Event Presentation Google Cloud Next Extended 2025
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
NewMind AI Weekly Chronicles - August'25 Week I
Chapter 3 Spatial Domain Image Processing.pdf
KodekX | Application Modernization Development
Web Security: Login Bypass, SQLi, CSRF & XSS.pptx
Dell Pro 14 Plus: Be better prepared for what’s coming
Chapter 2 Digital Image Fundamentals.pdf
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Top Generative AI Tools for Patent Drafting in 2025.pdf
A Day in the Life of Location Data - Turning Where into How.pdf
ABU RAUP TUGAS TIK kelas 8 hjhgjhgg.pptx
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
Belt and Road Supply Chain Finance Blockchain Solution
Understanding_Digital_Forensics_Presentation.pptx
CIFDAQ's Teaching Thursday: Moving Averages Made Simple
DevOps & Developer Experience Summer BBQ
CIFDAQ's Market Wrap: Ethereum Leads, Bitcoin Lags, Institutions Shift
CIFDAQ's Market Insight: SEC Turns Pro Crypto
Google’s NotebookLM Unveils Video Overviews
Event Presentation Google Cloud Next Extended 2025

ASP.MVC Training

  • 2. MVC PatternA architectural design pattern used in software engineeringAcronym for Model ● View ● ControllerOften seen in web applications but not limited to itDefIsolate 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 technologyScalableExtensibleFamiliar feel to WinForms developersLot of features like viewstate , rich controls support, page life cycle… but they have challengesAbstractions aren’t very abstractDifficult to testLack of control over markupIt does things you didn’t tell it to doSlow because of controls and page cycles
  • 5. ASP.NET MVC Framework GoalsUtilize ASP.NET architecture.Testability Loosely Coupled and extensibleTight control over markupUser/SEO friendly URLsAdopt REST conceptsLeverage the benefits of ASP.NETSeparation of concernsSRP – Single Responsibility PrincipleDRY – Don’t Repeat Yourself -Changes are limited to one placeHelps with concurrent developmentConvention over configuration
  • 6. What happend to WebformsNot a replacement for WebFormsAll about alternativesFundamentalPart of the System.Web namespaceSame team that builds WebFormsProviders still workMembership, Caching, Session, etc.Views leverage .aspx and .ascxBut they don’t have to if you don’t want them toFeature Sharing
  • 7. What is ASP.NET MVC?ControllerRequestStep 1Incoming request directed to Controller
  • 8. ModelWhat is ASP.NET MVC?ControllerStep 2Controller processes request and forms a data Model
  • 9. ViewWhat is ASP.NET MVC?ControllerViewStep 3Model is passed to View
  • 10. ViewWhat is ASP.NET MVC?ControllerViewStep 4View transforms Model into appropriate output format
  • 11. What is ASP.NET MVC?ControllerViewResponseStep 5Response is rendered
  • 12. ModelVCModel represents the business objects, the data of the application.Apart from giving the data objects, it doesn’t have significance in the frameworkYou can use any of the following technologies to build model objectsLINQ to Entities, LINQ to SQL,NHibernate, LLBLGen Pro, SubSonic, WilsonORMjust raw ADO.NET DataReaders or DataSets.
  • 13. MVControllerController is the core component in MVC which intercepts and process the requests with the help of views and modelsEvery controller has one or more Action methods.All requests are mapped to a public methods in a controller are called ActionsController 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. MViewCViews 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 viewDataViews page are extended from ASP.NET Page object.Can have server code with <% %> and client side code.Two types of viewsStronglyTypedModel object is available to access strongly typed object Inherits from System.Web.Mvc.ViewPage<Model>Generic view ViewData object is available to access ViewDataDictionaryInherits from System.Web.Mvc.ViewPageGenerally views are available in “views\Controllername” folder Views supports usercontrols and masterpages.WebFormViewEngineCan I use both model and viewdata same time?s
  • 15. Action methodTypically 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 views\Controller 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=carEvery method will return a instance of abstract class ActionResultor a derived classNot every methods members are Action methodsIf a method is with NonActionAttributeSpecial methods such as constructors, property assessors, and event assessors cannot be action methods.Methods originally defined on Object (such as ToString)
  • 16. ActionResultEvery method will return a class that derived from ActionResult abstract base classActionResultwill handle framework level work (where as Action methods will handle application logic)Lot of helper methods are available in controller for returning ActionResult instancesYou 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 ActionResultpublic abstract class ActionResult{ public abstract void ExecuteResult(ControllerContext context);}
  • 18. HTML Helper methodsSet 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 pattersAll 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. ValidationYou find the errors in the controller, how do you propagate them to the view?The answer is System.Web.Mvc.ModelStateDictionary ,ModelStateProcessYou have to add all error messages to ModelstateDictionary in Action methodHtml.ValidationMessage(“name”)Html.ValidationMessage(“Key” , ”Custom Error Message”)class=” field-validation-error” is used to show the messageHtml.ValidationSummary(“custom message”)Displays unordered list of all validation errors in the ModelState dictionaryclass=”validation-summary-errors” is used to format which is available in templateDo 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 BindersThese are user defined classes Used to define the strongly typed views of model objectsTo make easy of handling HTTP Post requests and helps in populating the parameters in action methods.Models are passed betweenAction method Strongly Typed ViewsUse 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 desiredSo 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..Validationuse the Controller.Modelstate.IsValid for errors checking. on post to a action method, Automatically Errors are added to the ModelstateModel Objects should always have error validation. Don’t depend on user post valuesHow controls state is maintained on posts?Return the same view with model , if there is a errorModel Binding tells input controls to redisplay user-entered valuesSo always use the HTML helper classesOnly basic controls are supported, you can create your own Helper methods
  • 22. Data passing between view and controller
  • 23. FiltersFilters handovers extra framework level responsibility to Controller/Action methodsAuthorize: 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 attributesControllerAction 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.NonActionAttributeAcceptVerbs AttributeThis is a concrete implementation of ActionSelectorAttributeThis 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. ErrorsHandleError 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 folderThis attribute will create and populate the System.Web.Mvc.HandleErrorInfoError.aspx is a strongly typed view of HandleErrorInfoEnable CustomErrors in web.configHow do you handle errors if the user tries to request a wrong URL??ApproachCreate a controller by name ErrorCreate a Action method with some error number/error/404Enable custom errors and specify redirect the url to Create a views to show the error messageRetrieve 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 capabilitiesTo 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 levelAjax Extensions are provided and are exposed with Ajax prop in a viewAjax.ActionLink()Ajax.BeginForm()At controller you can really identify the normal request and ajax request with property Request.IsAjaxRequest()x-requested-with: XMLHttpRequestCoding RulesEach 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 methodif action is not an AJAX request, Each Action should return a dedicated view/ redirect to a route.Only two classes AjaxExtensions , AjaxOptionsWe can call web services
  • 27. Clean URL StructureFriendlier to humansFriendlier to web crawlersSearch engine optimization (SEO)Fits with the nature of the webMVC exposes the stateless nature of HTTPREST-likehttp://www.store.com/products/Bookshttp://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/BooksRewriting : Rewriting is used to manipulate URL paths before the request is handled by the Web server. Page is fixedRouting: InRouting, urls are not changed but routed to a different handler pre defined. Url is fixed
  • 29. RoutesA route a URL with a structureRoutes 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.aspxRoutes 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 defaultsroutes.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 RoutesDefault value position is also importantThus, default values only work when every URL parameter after the one with the default also has a default value assignedAny route parameters other than {controller} and {action} are passed as parameters to the action method, if they exist
  • 31. Constraints with routesConstraints are rules on the URL segmentsAll the constraints are regular expression compatible with class Regexroutes.MapRoute(“blog”, “{year}/{month}/{day}“, new {controller=”blog”, action=”index”} , new {year=@“\d{4}“, month=@“\d{2}“, day=@“\d{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 LifecycleGet IRouteHandlerRequestFind the RouteGet MVCRouteHandlerMvcRouteHandlerGet HttpHandler from IRouteHandlerMvcHandlerCall IhttpHandler. ProcessRequest()ControllerRequestContextUrlRoutingModuleView
  • 34. Routing handlersMVCRouteHandlerStopRoutingHandlerrequests resolved with this handler is ignored by mvc and handovers the request to normal HTTP Handlerroutes.IgnoreRoute(“{resource}.axd/{*pathInfo}“);CustomRouteHandler
  • 35. Who takes the responsibility of calling a actionActionInvokerEvery 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 propertyMain TasksLocates 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. ExtensibleReplace any component of the systemInterface-based architecture Very few sealed methods / classesPlays well with othersWant 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 enginesnVelocity nhamlSpark Brail MVCContrib
  • 37. Dry Principle examplesUsing validation logic in both edit and createNotFound view template across create, edit, details and delete methodsEliminate 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 scenariosUser Controls are usedChanges are limited to one place
  • 38. References http://www.asp.net/mvc/http://stephenwalther.com/blog/category/4.aspx?Show=AllIIS 6, IIS7 Deploymentshttp://www.codeproject.com/KB/aspnet/webformmvcharmony.aspx