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

ASP.MVC Training

  • 1.
  • 2.
    MVC PatternA architecturaldesign 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
  • 3.
  • 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 FrameworkGoalsUtilize 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 toWebformsNot 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.NETMVC?ControllerRequestStep 1Incoming request directed to Controller
  • 8.
    ModelWhat is ASP.NETMVC?ControllerStep 2Controller processes request and forms a data Model
  • 9.
    ViewWhat is ASP.NETMVC?ControllerViewStep 3Model is passed to View
  • 10.
    ViewWhat is ASP.NETMVC?ControllerViewStep 4View transforms Model into appropriate output format
  • 11.
    What is ASP.NETMVC?ControllerViewResponseStep 5Response is rendered
  • 12.
    ModelVCModel represents thebusiness 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 thecore 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 theend 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 Actionmethod 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 willreturn 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);}
  • 17.
  • 18.
    HTML Helper methodsSetof 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 theerrors 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 areuser 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 theController.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 betweenview and controller
  • 23.
    FiltersFilters handovers extraframework 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 attributesControllerActionattribute 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 Markmethods 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 provideasynchronous 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 StructureFriendlierto 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 aURL 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 RoutesDefaultvalue 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 routesConstraintsare 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}
  • 32.
  • 33.
    The Request LifecycleGet IRouteHandlerRequestFind the RouteGet MVCRouteHandlerMvcRouteHandlerGet HttpHandler from IRouteHandlerMvcHandlerCall IhttpHandler. ProcessRequest()ControllerRequestContextUrlRoutingModuleView
  • 34.
    Routing handlersMVCRouteHandlerStopRoutingHandlerrequests resolvedwith this handler is ignored by mvc and handovers the request to normal HTTP Handlerroutes.IgnoreRoute(“{resource}.axd/{*pathInfo}“);CustomRouteHandler
  • 35.
    Who takes theresponsibility 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 componentof 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 examplesUsingvalidation 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