Monday, 26 September 2016

Chapter-3 Life Cycle of Asp.Net MVC




The life of an HTTP request as it travels through the MVC framework in ASP.NET.

MVC has two life cycles: 
1.       The application life cycle: refer to the time at which the application process actually begins running IIS until the time it stops.
2.       The request life cycle : every MVC application begins with routing. It is responsible for matching the incoming URL to routes that we define in our application. All routes have an associated route handler .  



The MVC framework request life cycle works by converting the route data into a concrete controller that can handle requests This is known as Action Execution with help of action invoker which find Action Method which triggers in result known as Result Execution. 
If the result is a view type, the View Engine will be called and it's responsible for finding and rending our view.

In the ASP.NET implementation of MVC:
1)      Incoming requests are handled by controllers, which are C# classes that contain methods.
2)      Each public method in a controller is referred to as an action method or a controller action.
3)      The action methods can be invoked by using a URL.
4)      When an HTTP request is sent to the server by using a URL:
a)      The controller action associated with the URL is executed to perform the required operation on a model.
b)      A view is rendered and displayed to the client,

Features of ASP.NET MVC
1)      Routing
2)      Scaffolding
3)      Convention-over-Configuration
4)      Bundling and Minification
Benefits provided by ASP.NET MVC
1)      Separation of concerns
2)      Simplified testing and maintenance
3)      Extensibility
Structure of an ASP.NET MVC Project

ASP.NET uses a hierarchy of configuration files to keep application configuration settings separate from the application code.
A configuration file provides the following benefits:
  1. Provides control and flexibility over the way you run applications.
  2. Eliminates the need to recompile the application every time a setting changes.
  3. Controls access to the protected resources and the location of remote applications and objects by defining configuration settings.
  4. The two files included in the hierarchy of configuration files are Machine.config and Web.config.
  5. The Machine.config file always resides at the root of the configuration hierarchy and contains the global and default settings for all the .NET Framework applications on the server.
  6. The Web.config file can reside at multiple levels in the hierarchy.
Routing :

1.       It is the process of directing an HTTP request to a controller and the functionality of this processing is implemented in System.Web.Routing.
2.       Routing is direct to a request to a controller.  


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing; 
namespace MVCFirstApp
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 
            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }
    }
}

Working with Controllers

1.       Controllers are essentially the central unit of your ASP.NET MVC application.
2.       Controllers decides which model will takes the data and passes to view, after that view is rendered.
3.       Controllers are C# classes inheriting from System.Web.Mvc.Controller.


Creating a Controller:

You can create a controller by:
  1. Creating a .cs file in the Controllers folder of the project.
  2. Inheriting the Controller class, as shown in the following code snippet:
public class HomeController : Controller
{
                //Some code
}

According to the ASP.NET MVC convention, the name of a controller is always suffixed by the word, Controller.

Creating Action Methods
  1. Action methods are public methods in the controllers.
  2. They handle user interactions with the application.
Example:

The following code snippet defines two action methods in a controller class:

public class HomeController : Controller
    {
        public ActionResult Index()
        {
           //Some code
        }
         public ActionResult About()
        {
                                //Some code
        }
     }

Invoking Controller Actions
  1. To invoke an action method, you can specify a URL in the Web browser.
  2. This URL contains the information about a controller and the action method within the controller.
Example:

Passing Parameters in Controller Actions

  1. While requesting for a Web page, you may need to specify information other than the name of the Web page.
  2. This additional information can be sent to the server in the form of a query string included in the URL.
Example:
The browse action method can access the value for the Category parameter by using its arguments as shown in the following code snippet:

  public string browse(string Category)
       {
         return ("Category is: " + Category);
       }

Simple example of Controller by creating a new ASP.Net MVC project

Step 1: Open the Visual Studio and click on File -> New -> Project menu option.
Step 2: From the left pane, select Templates -> Visual C# -> Web.
Step 3: In the middle pane, select ASP.NET Web Application.
Step 4: Enter the project name .Click on Ok .

Step 5: Click on checkbox the MVC checkbox in the ‘Add folders and core references for’ section and click Ok.
Step 6: Add EmployeeController by right-clicking on Controllers folder in the solution explorer. Select Add -> Controller.

It will display the Add Scaffold dialog.

Step 7: Select the MVC 5 Controller – Empty option and click ‘Add’ button.
The Add Controller dialog will appear

Step 8: Set the name to EmployeeController and click ‘Add’ button.


Now, in this application we will add a custom route for Employee controller with the default Route.  

Step 1: Go to “RouteConfig.cs” file under “App_Start” folder and add the following route.  

routes.MapRoute("Employee",
     "Employee/{name}",
     new { controller = "Employee", action = "Search", name = UrlParameter.Optional }); 

Following is the complete implementation of RouteConfig.cs file. 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing; 
namespace MVCControllerDemo
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 
            routes.MapRoute("Employee",
                "Employee/{name}",
                new { controller = "Employee", action = "Search", name = UrlParameter.Optional }); 
            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }
    }
} 

Step 2: Change the EmployeeController class using the following code. 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc; 
namespace MVCControllerDemo.Controllers
{
    public class EmployeeController : Controller
    {
        // GET: Employee
        public ActionResult Search(string name)
        {
            var input = Server.HtmlEncode(name);
            return Content(input);
        }
    }
}


Summary

1)      Some of the features of ASP.NET MVC are:
i)        Routing
ii)       Scaffolding
iii)     Convention-over-Configuration
iv)     Bundling and Minification
2)      ASP.NET uses a hierarchy of configuration files to keep application configuration settings separate from the application code.
3)      A configuration file is an XML file that contains configuration settings for an application and has a .config extension.
4)      Controllers are implemented in an MVC application as C# classes
inherited from .NET Framework’s built-in Controller class.
5)      The controllers are placed in a folder named Controllers under the Web application folder.
6)      To invoke an action method, you can specify a URL in the Web browser that contains the information about a controller and the action method within the controller.


I hope that the functionality of the above attribute is clear to you now. Now you can use this code in your application. If you have further question, just drop a line below and I will try to answer you as soon as possible.

Last but not least, connect with me on Twitter , Facebook , LinkedIn and Google+ for technical updates and articles news. We won’t spam or share your email address as we respect your privacy.




No comments:

Post a Comment