Skip to content
gpawade edited this page Feb 11, 2018 · 1 revision

MVC

MVC is an architectural pattern which separates the representation and user interaction. By using MVC pattern, we can develop applications that are more flexible to changes without affecting the other components of our application. It's contain three section -

  • Model - represent real world object & provide data to view.
  • View - responsible for look & feeel.
  • Controller - responsible for taking the end user request and loading the appropriate Model and View.

Feature

  • Clear separation of application concerns (Presentation and Business Logic).
  • It’s an extensible as well as pluggable framework.
  • It provides extensive support for URL Routing that helps to make friendly URLs (means friendly for human as well as Search Engines).
  • It supports for Test Driven Development (TDD) approach. Automated UI testing is possible because now the behind code (UI interaction code) has moved to a simple .NET class.

Life Cycle

REQUEST => UrlRoutingModule (intercept the request) => ROUTE Table => Route Handler(MvcRouteHandler) => MvcHandler(IHttpHandler) => ProccessRequest() => Controller (IController Factory) => Controller.Execute() => ActionInvoker => RESPONSE

  1. Fill Route - request are mapped to route table which in turn specify which controller and action to be invoked. If request is first request , then fill the route table in Routes Collection.
  2. Fetch Route - Depending on the URL sent “UrlRoutingModule” searches the route table to create “RouteData” object which has the details of which controller and action to invoke.
  3. Request context created - The “RouteData” object is used to create the “RequestContext” object.
  4. Controller instance created - This request object is sent to “MvcHandler” instance to create the controller class instance. Once the controller class object is created it calls the “Execute” method of the controller class.
  5. Creating Response object - This phase has two steps executing the action and finally sending the response as a result to the view

Controller

Action Method

Controllers have specific methods for each user actions. Each request coming to controller is for a specific Action Method.

ActionResult they return

ActionResultClass Hlper Method Return Type
ViewResult View Web page
JsonResult Json Retuns a serialized JSON object
RedirectResult Redirect Performs an HTTP redirection to a specified URL
ContentResult Content Returns a user-defined content type
JavaScriptResult JavaScript Returns a piece of JavaScript code that can be executed on the client
FileContentResult FileContent Returns a file to the client

Note - All public method in controller consider as a action method by default. Use NoAction attribute for non-action method.

[NoAction]
public void MyNonActionMethod() { }

Filter

MVC Support following action filter -

  • Authorization Filter : implement IAuthorizationFilter. Example - AuthorizeAttribute, RequireHttpsAttribute.
  • Action Filter : implement IActionFilter, has two method OnActionExecuting and OnActionExecuted. This run before & after action method.
  • Result Filter: implement IResultFilter, has two method OnResultExecuting and OnResultExecuted. e.g. OutputCacheAttribute.
  • Exception filter: implement IExceptionFilter. e.g. HandleErrorAttribute

Note - Controller class implment each of the filter interfaces. You can implement any of the filters for a specific controller by overriding the controller's On method.

####Create Filter

  • Override one or more of the controller's On methods.
  • Create an attribute class that derives from ActionFilterAttribute and apply the attribute to a controller or an action method.
  • Register a filter with the filter provider (the FilterProviders class).
  • Register a global filter using the GlobalFilterCollection class.

Register Global Filter This filter will execute for every action in all controller.

// in appliation_start
GlobalFilters.Filters.Add(new FooFilter());
GlobalFilters.Filters.Add(new BarFilter());

FilterProvider New feature of MVC3. They are a "multiply registered" style service, with a static registration point at FilterProviders.Providers. This collection provides a facade method (GetFilters*) which aggregates the filters from all of the providers into a single list. Order of the providers is not important.

  • Filter provider class creaeted using IFilterProvider interface.

Route

Routing helps you to define a URL structure and map the URL with the controller. ASP.NET MVC framework uses a routing engine, that maps URLs to controller classes. We can define routing rules for the engine, so that it can map incoming request URLs to appropriate controller. When a user types a URL in a browser window for an ASP.NET MVC application and presses “go” button, routing engine uses routing rules that are defined in Global.asax file in order to parse the URL and find out the path of corresponding controller.

Route Declaration

// in appliation_start
RouteConfig.RegisterRoutes(RouteTable.Routes);

public static void RegisterRoutes(RouteCollection routes)
{
  routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

  routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
  );
}

Attribute based Routing

New feature in asp.net 5. By using the "Route" attribute we can define the URL structure.

public class HomeController : Controller
{
       [Route("home/about")]
       public ActionResult GotoAbout()
       {
           return View();
       }
}

In above example the route attribute says that the "GotoAbout" can be invoked using the URL structure "home/about".

Advantage -

  • Developers can see the URL structure right upfront rather than going to the “routeconfig.cs”.
  • This is much user friendly as compared to scrolling through the “routeconfig.cs”

Route Contraint

You use route constraints to restrict the browser requests that match a particular route. You can use a regular expression to specify a route constraint.

routes.MapRoute(
    "Product",
    "Product/{productId}",
    new {controller="Product", action="Details"},
    new {productId = @"\d+" }
 );

The regular expression \d+ matches one or more integers. This constraint causes the Product route to match the following URLs:

  • /product/123
  • /product/4545

Custom Route Contraint

A custom route constraint enables you to prevent a route from being matched unless some custom condition is matched.

public class LocalhostConstraint : IRouteConstraint
{
    public bool Match( HttpContextBase httpContext,  Route route, 
                string parameterName, RouteValueDictionary values, RouteDirection routeDirection )
    {
        return httpContext.Request.IsLocal;
    }
}

// in route declaration
routes.MapRoute(
                "Admin",
                "Admin/{action}",
                new {controller="Admin"},
                new {isLocal=new LocalhostConstraint()}
            );    

Areas

Areas help you to group functionalities in to independent modules thus making your project more organized.

View

Why Razor

Razor is clean, lightweight, and syntaxes are easy as compared to ASPX.

ViewData, ViewBag and TempData

In order to pass data from controller to view and in next subsequent request, ASP.NET MVC framework provides different options. Both ViewBag and ViewData are used to communicate between controller and corresponding view. But this communication is only for server call, it becomes null if redirect occurs. So, in short, it's a mechanism to maintain state between controller and corresponding view. ViewData is a dictionary object while ViewBag is a dynamic property (a new C# 4.0 feature).

TempData is also a dictionary object that stays for the time of an HTTP Request. So, Tempdata can be used to maintain data between redirects, i.e., from one controller to the other controller or from one action to another action. If “TempData” is once read it will not be available in the subsequent request. If you want to persist it then use Keep.

var val = TempData["My_Data"];
TempData.Keep("My_Data"];

// more shortcut  way of achiving same is by using Peek.
string str = TempData.Peek("My_Data").ToString();

####_viewstart.cshtml

  • _viewstart file exist under View folder.
  • _viewstart view run before every view executing.
  • From controller, you called PartialView(), then _viewstart won't be executed. It'll be executed only when you called View() from controller.

Layout file

  • @RenderBody()
  • @RenderSection()

HTML Helper

HTML helpers help you to render HTML controls in the view.

Partial View

  • Partial view is a reusable view (like a user control) which can be embedded inside other view.
  • The partial view therefore has access to the data of the parent view.

RenderPartial Vs RenderAction Vs Partial Vs Action

RenderPartial

  • This method result will be directly written to the HTTP response stream.
  • This method returns void. Simple to use and no need to create any action.
  • This method is faster than Partial method since its result is directly written to the response stream which makes it fast.
  • Use same model which use parent view.
    @{Html.RenderPartial("_Comments");}

RenderAction

  • This method result will be directly written to the HTTP response stream.
  • For this method, we need to create a child action for the rendering the partial view.
  • This method is the best choice when you want to cache a partial view.
  • This method is faster than Action method since its result is directly written to the HTTP response stream which makes it fast.
    @{Html.RenderAction("Category","Home");} 

Partial

  • Renders the partial view as an HTML-encoded string.
  • This method result can be stored in a variable, since it returns string type value.
  • Simple to use and no need to create any action.
    @Html.Partial("_Comments")

Action

  • Renders the partial view as an HtmlString .
  • For this method, we need to create a child action for the rendering the partial view.
  • This method result can be stored in a variable, since it returns string type value.
  • This method is also the best choice when you want to cache a partial view.
    @{Html.Action("Category","Home");} 

Caching

Caching provides a way of storing frequently accessed data and reusing that data.

  • Output Cache Filter

The OutputCache filter allow you to cache the data that is output of an action method. By default, this attribute filter cache the data till 60 seconds.

[OutputCache(Duration=20, VaryByParam="none"]
public ActionResult Index()
{
    return View();   
}

Output of the Index() action method will be cache for 20 second. Properties -

  • Duration
  • VaryByParam
  • VaryByHeader
  • VaryByCustom
  • NoStore - Enable/Disable where to use HTTP Cache-Control. This is used only to protect very sensitive data.
  • Location - Specify the location of the output to be cached.By default, content is cached in three locations: the web server, any proxy servers, and the user's browser. Value option -
    • Any
    • Client
    • Downstream
    • Server
    • None
    • ServerAndClient

Web API

WebAPI is the technology by which you can expose data over HTTP following REST principles.

WCF vs Web API

WCF was brought into implement SOA, the intention was never to implement REST. WebAPI is built from scratch and the only goal is to create HTTP services using REST. Due to the one point focus for creating REST service, WebAPI is more preferred.