Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

ASP.MVC Training

5,044 views

Published on

Published in: Technology

ASP.MVC Training

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

×