ASP.net MVC

Page Lifecycle

  • App Initialization
  • Url Routing Module
  • MVC Rout Handler HttpHandler
  • Instantiate and execute controller -> DefaultControllerFactory: IControllerFactory
  • Locate and invoke controller action -> IActionInvoker
  • Instantiate and render view.

advantages of ASP.Net MVC over ASP.NET?

  • Provides a clean separation of concerns
  • Easy to UNIT Test
  • Improved reusability of model and views
  • Improved structuring of the code.

What is Razor View Engine

Code-focused templating for HTML generation.

Unobtrusive JavaScript

  • Unobtrusive JavaScript doesn't inter mix JavaScript code in your page markup
  • It attaches to elements by their ID or class

What is Routing

Pattern matching mechanism of incoming requests to the URL patterns which are registered in route table.

Attribute Routing

attributes are being used to define the routes

cs [Route("{action = TestCategoryList}")] - Controller Level [Route("customers/{TestCategoryId:int:min(10)}")] - Action Level

It has to be enabled while registering Rotes

What are Actions

  • Actions are the methods in Controller class which is responsible for returning the view or json data

Methods Used for rendering

  • View() : To return the view from action.
  • PartialView() : To return the partial view from action.
  • RedirectToAction() : To Redirect to different action which can be in same controller or in different controller.
  • Redirect() : Similar to "Response.Redirect()" in webforms, used to redirect to specified URL.
  • RedirectToRoute() : Redirect to action from the specified URL but URL in the route table has been matched.

What are the sub types of ActionResult

  • ViewResult
  • PartialViewResult
  • RedirectToRouteResult
  • RedirectResult
  • JavaScriptResult
  • JSONResult
  • FileResult
  • HTTPStatusCodeResult

How does MVC Request Processing Works

  1. MVC used UrlRoutingModule : IHttpModule from System.Web.Routing which is also used in ASP.net
  2. UrlRoutingModule registers for PostResolveRequestCache event. ( Ideally should use the MapRequestHandler event. However, MapRequestHandler is not available in II6 or IIS7 ISAPI Mode and PostResolveRequestCache is the event immediately before MapRequestHandler. So using this allows use to use one common codepath for all versions of IIS.)
  3. MvcRouteHanddler
    • Routing Engine is agnostic
  4. MvcHandler
    • IControllerFactory
    • Creates controller
    • Executes Controller
    • Dispose Controller
  5. IController
    • Lowest Level abstraction
    • MvcController

Http Handlers & Modules

Http Handlers

The Extension Based Preprocessor

  • inject Pre-Processing logic based on the extension of the file name requested.
  • executes on the base of extension file names and on the base of verbs
  • can also map one handler to multiple file extensions
  • How to Implement HttpHandler

    1. Implement IHttpHandler and the main method of concern is ProcessRequest(HttpContext) where we can decide what to return form the request.
    2. Need to tell the framework when to call this handler by making an entry in the configuration

      xml <system.web> <httpHandlers> <add verb="*" path="*.piyush,*.wink" type="MyPipeLine.clsMyHandler, MyPipeLine"/> </httpHandlers> </system.web>

Http Module

The Event Based Preprocessor

  • Modules are called before and after the handler executes
  • It helps to intercept, participate in, or modify each individual request.
  • Available Events:
    • BeginRequest
    • AuthenticateRequest
    • AuthorizeRequest
    • ResolveRequestCache: to determine whether to serve the page from the cache.
    • AcquireRequestState: to build your own Session state management module,
    • PreRequestHandlerExecute
    • PostRequestHandlerExecute
    • ReleaseRequestState: To store session state back to store. If you are building a custom session state module, you must store your state back in your state store.
    • UpdateRequestCache: To write output back to the Output cache
    • EndRequest: Request has been completed. You may want to build a debugging module that gathers information throughout the request and then writes the information to the page.

Controller

  • Should Implement IController which contains only one method Execute()
  • Controller in MVC implements IController along with many other interfaces like

    IActionFilter, IAuthenticationFilter, IAuthorizationFilter, IDisposable, IExceptionFilter, IResultFilter, IAsyncController, IController, IAsyncManagerContainer

  • Default ControllerFactory only allows Controllers with Default Constructor

  • Extensibility: IControllerFactory can be overridden to provide custom implementation
    • GetControllerType()
    • GetControllerInstance()
    • Use ControllerBuilder to change the default Builder by calling static SetControllerFactory()

Actions

  • pre and post execution
  • Feature Added by System.Web.Mvc.Controller
  • IActionInvoker to select the Action inside a Controller

Action Verbs:

  • ActionName: Name of Action Mapped to the Function
  • AcceptVerb: POST, GET

Action Parameters

For Primitive types

  • Map from Route Data
  • Map from Form Data
  • Map from Query String
  • If parameter is not found a null reference is passed

Filter Attributes

Allow to inject Pre and post processing logic

  • OutputCache
  • ValidateInput
  • Authorize
  • ValidateAntiForgeryToken
  • HandleError

Different ways of Rendering partial Views

  • Action
  • Render;

Difference between RenderAction, RenderPartial, Partial and Action

  • Action: Bound to an Action in Controller. Used when displaying unrelated Data that you don't have already.....
  • Partial: Directly View is rendered without going through the Controller. Used when you already have the Data to be displayed.
  • RenderAction: Same as Action but directly written to HTTP response stream. Returns void.
  • RenderPartial: Same as Partial but directly written to HTTP response stream. Returns Void