Codechef4u is a community for computer professionals,by computer professionals,just like you; who loves sharing and helping each others,Join them
Share your post

MVC application life cycle

MVC application life cycle

Point to Remember:
There is nothing like MVC application life cycle.To be specific the MVC request goes through various steps of execution & that’s what is termed as MVC application life cycle.

 Any web application has two main execution steps

1.  Request (HTTP Request)
2.  Response (HTTP Response)

MVC application life cycle is not different it has two main phases first creating the request object and second sending our response to the browser.

Creating the request object:  The request object creation has four major steps.

Following Steps explains in Detail:

Step 1 Fill route:  MVC requests are mapped to route tables which in turn specify which controller and action to be invoked. So if the request is the first request the first thing is to fill the route table with routes collection. This filling of route table happens in the global.asax file.

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

Step 3 Request context created:  The “RouteData” object is used to create the “RequestContext” object.

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

Creating Response object:   This phase has two steps executing the action and finally sending the response as a result to the view.

Step 1 Execute Action:  The “ControllerActionInvoker” determines which action to executed and executes the action.

Step 2 Result sent:  The action method executes and creates the type of result which can be a view result, file result, JSON result etc.

So in all there are six broad steps which get executed in MVC application life cycle.

Note:  In case you are not able to remember the above steps remember the acronym FFRCER (Fight For Respect Can Evoke Revolution).

 Example:

Route table for execution path in global.ascx

  public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
 
 
            routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new { controller = "Account", action = "LogOn", id = UrlParameter.Optional } //Parameter defaults
            );
 
        }

Register route :

protected void Application_Start()
        {
            RegisterRoutes(RouteTable.Routes);
        }

Suppose your web application is running on www.codechef4u.com then the url pattren for you application will be www.codechef4u.com /{controller}/{action}/{id}.

i.e  http:// codechef4u.com/Account /UserDateils /1

Route explains:

Controller:  Account
Action : UserDateils
Value :1

MVC routing

In this article we explained in detail important asp.net MVC feature called routing.

The ASP.NET Routing module is responsible for mapping incoming browser requests to particular MVC controller actions.At runtime, Routing engine use the Route table for matching the incoming request's URL pattern against the URL patterns defined in the Route table.

Using the default route table:

A route table is created in the application's Global.asax file. The Global.asax file is a special file that contains event handlers for ASP.NET application lifecycle events. The route table is created during the Application Start event.

public static void RegisterRoutes(RouteCollection routes)
{
     routes.IgnoreRoute("{resource}.axd/{*pathInfo}");      
 
     routes.MapRoute("Default", // Route name
     "{controller}/{action}/{id}", // URL with parameters
      new { controller = "Account", action = "LogOn", id = UrlParameter.Optional              } // Parameter defaults(Default values for parameters)
);
 
        }


How it works:

When an MVC application first starts, the Application_Start() method is called. This method, in turn, calls the RegisterRoutes() method. The RegisterRoutes() method creates the route table.

1.  Default route table maps first part of URL to controller name, in above example that’s Default.
2.  Default route table maps second part of URL to controller action in above example default action is logon.
3.  Default route table maps third part of URL to id that’s optional.

Example:

If you enter the below URL into your web browser's address bar:

  www.elave.com/LeaveManager/Detail/2

 The Default route maps this URL to the following parameters:

     a.  controller = LeaveManagerController
b.  action = Detail
c.  id = 2

When you request the www.elave.com/LeaveManager/Detail/2, the following code is executed:

LeaveManagerController.Detail(2)


Default values in above example:

If you don't supply a controller, then the controller parameter defaults to the value Account. If you don't supply an action, the action parameter defaults to the value LogOn. Finally, if you don't supply an id, the id parameter defaults to an empty string.

Example with DepartmentController:

Requests by user:
1.  www.leave-example.com/Department/index (index action with no parameter)
2.  www.leave-example.com/Department/Details/1 (Details action with parameter value 1)

In following code you can check two actions Index with no parameter value and Detail with parameter value.

   

   public class DepartmentController : Controller
    {
        private UnituOfWork unitOfWork = new UnituOfWork();
        //
        // GET: /Leave/
 
        public ActionResult Index()
        {
            var Departments = unitOfWork.GetAllDepartments();
            return View(Departments);
        }
 
 
       
        public ActionResult Detail(int id)
        {
            Department Departmentr = unitOfWork.departmentRepository.GetByID(id);
 
            return View(Departmentr);
 
        }
 
        public Guid GetUser()
        {
            MembershipUser user = Membership.GetUser(HttpContext.User.Identity.Name);
            Guid userid = (Guid)user.ProviderUserKey;
            return userid;
        }
 
    }
 

A partial view

Introduction:

In asp.net Web form naturally we create reusable components using asp.net user controls (i.e. UserDetail.ascx) or web server controls.

With MVC model for same purpose we use partial view. While ASP.NET MVC partial views may behave similarly in theory to web user controls, syntactically and functionally, the two behave differently.

Asp.net user control supports view state, post backs and events while MVC partial views do not use any of these techniques.

Partial view description:

A partial view enables you to define a view that will be rendered inside a parent view. When a partial view is instantiated, it gets its own copy of the ViewDataDictionary object that is available to the parent view.

HTML helper provides an extension method called Html.Partial to render partial views. Below explained different flavors of Partial method:

a.  @Html.Partial(string partialViewName):Renders the given partial view content into the referred view.
b.   @Html.Partial(string partialViewName,object model):Renders the partial view content into the referred view. Model parameter passes the model object to the partial view.
c.  @Html.Partial(string partialViewName, ViewDataDictionary viewData):Renders the partial view content into the referred view. View data parameter passes view data dictionary to the partial view.
d.  @Html.Partial(string partialViewName,object model, ViewDataDictionary viewData): Renders the partial view content into the referred view. Model parameter passes the model object and View data passes view data dictionary to the partial view.

Points to remember:

 1. Partial view has access to parent view data.
 2. If you update partial view, those updates affect only the partial view's ViewData object.
 3. View state is not supported in partial view.
 4. @Html.Partial() HTML helper renders the given partial view into the current view.

 

Example:

Create partial view:

To create a partial view, right click the /Views/Shared folder > Add > View. Type a View Name, type or choose a class from the Model class and check the Create as a partial view option, as shown below


Click Add and a partial view file at Views/Shared/UserLeaveSummery.cshtml gets created.


Inserting Partial Views into parent view:

Parent view (Index.cshtml)

@model System.Collections.Generic.List<BlogProj.Models.ViewModel.ViewLeaveDetails>
 
@using System.Web.Mvc.Html
@{
    ViewBag.Title = "Home Page";
}
 
<div style="height:25px"></div>
<h2>@ViewBag.Message</h2>
 
<div><p>here parent view data you can add other logic </p>
 </div>
<div>
 <p>partial view called </p>
    @Html.Partial("~/Views/shared/UserLeaveSummery.cshtml",Model)
</div>

 

Partial view (UserLeaveSummery.cshtml):

@model System.Collections.Generic.List<BlogProj.Models.ViewModel.ViewLeaveDetails>
 
 <table class="ui-widget-content" style="border-spacing:0px;font-size:15px; font-family:Verdana">
 
    <tr class="ui-widget-header">
        
         <th>
         Type
        </th>
            <th>
         Remaining
        </th>
          <th>
         Approved
        </th>
         <th>
         Pending
        </th>
 
    </tr>
         
@foreach (var item in Model)
{
    <tr>
  
       <td>
          @Html.DisplayFor(modelItem=> item.Leavetype)
         
        </td>
        <td style="text-align:center">
            @Html.DisplayFor(modelItem=> item.RemainingLeaves)
        </td>
 
         <td style="text-align:center">
            @Html.DisplayFor(modelItem=> item.ApprovedLeaves)
        </td>
        <td style="text-align:center">
            @Html.DisplayFor(modelItem=> item.PendingForApprovel)
        </td>
       
   </tr>
}
 
</table>
    


Model:

public class ViewLeaveDetails
    {
        public string Leavetype { get; set; }
        public int LeavetypeId { get; set; }
        public int RemainingLeaves { get; set; }
        public int ApprovedLeaves { get; set; }
        public int PendingForApprovel { get; set; }
    }


Home Controller Action (Index event returns partial view model data):

private UnituOfWork unitOfWork = new UnituOfWork();
        public ActionResult Index()
        {
            var LeavesDetail =unitOfWork.LeaveDetails(GetUser());
            ViewBag.Message = " Welcome to Easy Leave HR solution";
 
            return View(LeavesDetail);
        }
 
        public Guid GetUser()
        {
            MembershipUser user = Membership.GetUser(HttpContext.User.Identity.Name);
            Guid userid = (Guid)user.ProviderUserKey;
 
            return userid;
        }

 

DLL Method returns leave details:

        public List<ViewLeaveDetails> LeaveDetails(Guid userId)
        {
            List<ViewLeaveDetails> Details = new List<ViewLeaveDetails>();
            using (ApplicationServices BlogDbContext = new ApplicationServices())
            {
                using (var con = new SqlConnection(BlogDbContext.Database.Connection.ConnectionString))
                {
                    // var con = (SqlConnection)BlogDbContext.Database.Connection;
                    con.Open();
                    using (SqlCommand storedProcCommand =
                    new SqlCommand("LeaveDetails", con))
                    {
                        storedProcCommand.CommandType = CommandType.StoredProcedure;
                        storedProcCommand.Parameters.Add("@TotalLeaves", SqlDbType.Int);
                        //Uncomment this line to return the proper output value.
                        storedProcCommand.Parameters["@TotalLeaves"].Direction = ParameterDirection.Output;
                        storedProcCommand.Parameters.AddWithValue("@userId", userId);
                        var dr =
                            storedProcCommand.ExecuteReader();
                        var test = storedProcCommand.Parameters["@TotalLeaves"].Value;
                        while (dr.Read())
                        {
                            ViewLeaveDetails Detail = new ViewLeaveDetails();
                            if (dr["LeaveTitle"] != DBNull.Value)
                            {
                                Detail.Leavetype = (string)dr["LeaveTitle"];
                                Detail.LeavetypeId = (int)dr["LeaveTypeid"];
                                Detail.RemainingLeaves = (int)dr["Leaves"];
                                if (dr["PendingLeaves"] != DBNull.Value)
                                {
                                    Detail.PendingForApprovel = (int)dr["PendingLeaves"];
                                }
                                else
                                {
                                    Detail.PendingForApprovel = 0;
                                }
                                if (dr["ApprovedLeaves"] != DBNull.Value)
                                {
                                    Detail.ApprovedLeaves = (int)dr["ApprovedLeaves"];
                                }
                                else
                                {
                                    Detail.ApprovedLeaves = 0;
                                }
                            }
 
                            Details.Add(Detail);
                        }
                    }
 
                }
 
            }
            return Details;
        }