Friday, May 10, 2013

MVC Basic Fundamentals

MVC Fundamentals
 

MVC is architectural pattern which separates the representation and the user interaction. It’s divided in three broader sections, “Model”, “View” and “Controller”. Below is how each one of them handles the task.
· View” is responsible for look and feel.
The Model is responsible for providing all the required business logic and validation to the view. The view is only responsible for displaying the data that is received from the controller as the result.
Moreover, views in Asp.Net MVC, handles the UI presentation of data as the result of a request received by a controller.

· Model” represents the real world object and provides data to the “View”.
The Model represents a set of classes that describes the business logic and data. It also defines business rules for how the data can be changed and manipulated Moreover, models in Asp.Net MVC, handles the Data Access Layer by using ORM tools like Entity Framework or NHibernate etc. By default, models are stored in the Models folder of the project.

·Controller” is responsible to take the end user request and load the appropriate “Model” and “View”. It controls all actions requested by users.
The Controller is responsible for controlling the application logic and acts as the coordinator between the View and the Model. The Controller receives input from users via the View, then process the user's data with the help of Model and passing the results back to the View.

Moreover, controllers in Asp.Net MVC respond to HTTP requests and determine the action to take based upon the content of the incoming request.

So finally we have the following conclusions.

Model–view–controller (MVC) is a software architecture pattern which separates the representation of information from the user's interaction with it.

The model consists of application data, business rules, logic, and functions.
A view can be any output representation of data, such as a chart or a diagram. Multiple views of the same data are possible, such as a bar chart for management and a tabular view for accountants.

The controller mediates input, converting it to commands for the model or view. The central ideas behind MVC are code reusability and separation of concerns.

The page lifecycle of an ASP.NET MVC page is explained as follows:

i) App Initialisation
In this stage, the aplication starts up by running Global.asax’s Application_Start() method.
In this method, you can add Route objects to the static RouteTable.Routes collection.
If you’re implementing a custom IControllerFactory, you can set this as the active controller factory by assigning it to the System.Web.Mvc.ControllerFactory.Instance property.

ii) Routing
Routing is a stand-alone component that matches incoming requests to IHttpHandlers by URL pattern.
MvcHandler is, itself, an IHttpHandler, which acts as a kind of proxy to other IHttpHandlers configured in the Routes table.

iii) Instantiate and Execute Controller
At this stage, the active IControllerFactory supplies an IController instance.

iv) Locate and invoke controller action
At this stage, the controller invokes its relevant action method, which after further processing, calls RenderView().

v) Instantiate and render view
At this stage, the IViewFactory supplies an IView, which pushes response data to the IHttpResponse object.

Here is more details for MVC request life cycle:
Requests to an ASP.NET MVC-based Web application first pass through the UrlRoutingModule object, which is an HTTP module. This module parses the request and performs route selection. The UrlRoutingModule object selects the first route object that matches the current request. (A route object is a class that implements RouteBase, and is typically an instance of the Route class.) If no routes match, the UrlRoutingModule object does nothing and lets the request fall back to the regular ASP.NET or IIS request processing.
From the selected Route object, the UrlRoutingModule object obtains an object that implements the IRouteHandler interface and that is associated with theRoute object. Typically, in an MVC application, this will be an instance of the MvcRouteHandler class. The MvcRouteHandler instance creates an MvcHandlerobject that implements the IHttpHandler interface. The MvcHandler object then selects the controller that will ultimately handle the request. For more information, see ASP.NET Routing.
Note:
When an ASP.NET MVC Web application runs in IIS 7.0, no file name extension is required for MVC projects. However
, in IIS 6.0, the handler requires that you map the .mvc file name extension to the ASP.NET ISAPI DLL.
The UrlRoutingModule and MvcRouteHandler classes are the entry points to the ASP.NET MVC framework. They perform the following actions:
·         Select the appropriate controller in an MVC Web application.
·         Obtain a specific controller instance.
·         Call the controller's Execute method.
The following table lists the stages of execution for an MVC Web project.
Stage
Details
Receive first request for the application
In the Global.asax file, Route objects are added to the RouteTable object.
Perform routing
The UrlRoutingModule module uses the first matching Route object in the RouteTable 
collection to create the RouteData object, which it then uses to create a RequestContext object.
Create MVC request handler
The MvcRouteHandler object creates an instance of the MvcHandler class and passes
the RequestContext instance to the handler.
Create controller
The MvcHandler object uses the RequestContext instance to identify the IControllerFactory 
object (typically an instance of theDefaultControllerFactory class) to create the controller
 instance with.
Execute controller
The MvcHandler instance calls the controller's Execute method.
Invoke action
For controllers that inherit from the ControllerBase class, the ControllerActionInvoker 
object that is associated with the controller determines which action method of the
controller class to call, and then calls that method.
Execute result
The action method receives user input, prepares the appropriate response data, and then
executes the result by returning a result type. The built-in result types that can be
executed include the following: ViewResult (which renders a view and is the most-often
 Understanding Controllers

MVC controllers are responsible for responding to requests made against an ASP.NET MVC website. Each browser request is mapped to a particular controller. For example, imagine that you enter the following URL into the address bar of your browser:
http://localhost/Product/Index/8

In this case, a controller named ProductController is invoked. The ProductController is responsible for generating the response to the browser request. For example, the controller might return a particular view back to the browser or the controller might redirect the user to another controller.

using System.Web.Mvc;
namespace MvcApplication1.Controllers
{
public class ProductController : Controller
{
        // GET: /Products/

  public ActionResult Index()

          {

          // Add action logic here

          return View();

}          }

}
Understanding Controller Actions:






A controller exposes controller actions. An action is a method on a controller that gets called when you enter a particular URL in your browser address bar. For example, imagine that you make a request for the following URL:
In this case, the Index() method is called on the ProductController class. The Index() method is an example of a controller action.
Some important point about controller:
1.       A controller action must be a public method of a controller class. C# methods, by default, are private methods.
2.       A method used as a controller action cannot be overloaded. Furthermore, a controller action cannot be a static method.
3.       Action methods typically have a one-to-one mapping with user interactions.
Understanding Action Results
A controller action returns something called an action result. An action result is what a controller action returns in response to a browser request.
The ASP.NET MVC framework supports several types of action results including:
1.       ViewResult - Renders a specified view to the response stream
2.       PartialViewResult - Renders a specified partial view to the response stream
3.       EmptyResult - An empty response is returned
4.       RedirectResult - Performs an HTTP redirection to a specified URL
5.       RedirectToRouteResult - Performs an HTTP redirection to a URL that is determined by the routing engine, based on given route data
6.       JsonResult - Serializes a given ViewData object to JSON format
7.       JavaScriptResult - Returns a piece of JavaScript code that can be executed on the client
8.       ContentResult - Writes content to the response stream without requiring a view
9.       FileContentResult - Returns a file to the client
10.   FileStreamResult - Returns a file to the client, which is provided by a Stream
11.   FilePathResult - Returns a file to the client
All of these action results inherit from the base ActionResult class.
·         In most cases, a controller action returns a ViewResult.
·         When an action returns a ViewResult , HTML is returned to the browser.
For example 1:
namespace MvcApplication1.Controllers
{
    public class BookController : Controller
    {
       public  ActionResult  Index()
       {
        // Add action logic here
            return View();
       }
   }
}
Note: The Index() action does not return a ViewResult(). Instead, the View() method of the Controller base class is called. Normally, you do not return an action result directly. Instead, you call one of the following methods of the Controller base class:
1.       View - Returns a ViewResult action result.
2.       Redirect - Returns a RedirectResult action result.
3.       RedirectToAction - Returns a RedirectToRouteResult action result.
4.       RedirectToRoute - Returns a RedirectToRouteResult action result.
5.       Json - Returns a JsonResult action result.
6.       JavaScriptResult - Returns a JavaScriptResult.
7.       Content - Returns a ContentResult action result.
8.       File - Returns a FileContentResult, FilePathResult, or FileStreamResult depending on the parameters passed to the method.
v  So, if you want to return a View to the browser, you call the View() method. If you want to redirect the user from one controller action to another, you call the RedirectToAction() method.
For example 2:
namespace MvcApplication1.Controllers
{
  public class CustomerController : Controller
  {
    public ActionResult  Details(int? id)
    {
       if (!id.HasValue)
         return RedirectToAction("Index");
       return View();
    }
   public ActionResult  Index()
    {
      return View();
    }}}
For above example 2, the Details() action either displays a view or redirects the user to the Index() action depending on whether the Id parameter has a value.
v  The ContentResult action result is special. You can use the ContentResult action result to return an action result as plain text. For example, the Index() method in Listing 4 returns a message as plain text and not as HTML.
For example 3:
namespace MvcApplication1.Controllers
{
public class StatusController : Controller
{
public ActionResult  Index()
{
return Content("Hello World!");
}
}
}
When the StatusController.Index() action is invoked, a view is not returned. Instead, the raw text "Hello World!" is returned to the browser.
v  If a controller action returns a result that is not an action result - for example, a date or an integer - then the result is wrapped in a ContentResult automatically. For example, when the Index() action of the WorkController  is invoked, the date is returned as a ContentResult automatically.
namespace MvcApplication1.Controllers
{
public class WorkController : Controller
{
public  DateTime  Index()
{
return  DateTime.Now;
}
}
}
The Index() action above returns a DateTime object. The ASP.NET MVC framework converts the DateTime object to a string and wraps the DateTime  value in a ContentResult automatically. The browser receives the date and time as plain text.
Important Note: So controller action result can also return string or integer type value.
ActionResult  return type:
Most action methods return an instance of a class that derives from ActionResult. The ActionResult class is the base for all action results. However, there are different action result types, depending on the task that the action method is performing. For example, the most common action is to call the View method. The View method returns an instance of the ViewResult class, which is derived from ActionResult.
You can create action methods that return an object of any type, such as a string, an integer, or a Boolean value. These return types are wrapped in an appropriate ActionResult type before they are rendered to the response stream.
The following table shows the built-in action result types and the action helper methods that return them.

Action Result

Helper Method

Description



Renders a view as a Web page.



Renders a partial view, which defines a section of a

 view that can be rendered inside another view.



Redirects to another action method by using its URL.




Redirects to another action method.



Returns a user-defined content type.



Returns a serialized JSON object.



Returns a script that can be executed on the client.



Returns binary output to write to the response.


(None)

Represents a return value that is used if the action

method must return  a null result (void).
Some other information about MVC:
MVC is often seen in web applications, where the view is the actual HTML page, and the controller is the code that gathers dynamic data and generates the content within the HTML. Finally, the model is represented by the actual content, usually stored in a database or XML files, and the business rules that transform that content based on user actions.
Though MVC comes in different flavours, control flow generally works as follows:
1.       The user interacts with the user interface in some way (e.g. presses a button).
2.       A controller handles the input event from the user interface, often via a registered handler or callback.
3.       The controller notifies the model of the user action, possibly resulting in a change in the model's state. (e.g.controller updates user's shopping cart).
4.       A view uses the model (indirectly) to generate an appropriate user interface (e.g. the view produces a screen listing the shopping cart contents). The view gets its own data from the model. The model has no direct knowledge of the view.
5.       The user interface waits for further user interactions, which begins the cycle anew.
By decoupling models and views, MVC helps to reduce the complexity in architectural design, and to increase flexibility and reuse.
Marking Public Methods as Non-Action Methods:
By default, the MVC framework treats all public methods of a controller class as action methods. If your controller class contains a public method and you do not want it to be an action method, you must mark that method with the NonActionAttribute attribute.
The following example shows a method that is marked with the NonAction attribute.
[NonAction]
private void DoSomething()
{
    // Method logic.
}