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
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