Home > ASP.NET, Architecture & Design > MVC Architechture in ASP.Net-A Design Approach

MVC Architechture in ASP.Net-A Design Approach

February 27th, 2008

MVC architecture consists of Model, View and the Controller. Model is the common app logic which will insert, update, delete and modify data into/from suitable data source.View would be the GUI.Controller is the heart, is what we will discuss upon.

When developing complex dynamic ASP.NET applications, it’s important to minimize code duplication to increase the reusability, scalability and flexibility of the application. In some applications, users may perform many different actions that have various controller logic but result in the same view (UI).

In order to develop reusable logic we have to minimizing the amount of server side code in the code behind pages as they pertain to a single object i.e. they are the controller for a single page. The logic on code behind and scripted pages is difficult or impossible to reuse and results in poor separation between the view and the controller. The active server scriplets are also more difficult to test and debug, additionally they defy the basic ASP.NET feature of pre-compiling of code as they are compiled and translated at run. Instead of adding script code to an .aspx page, it’s more efficient to implement the controller using classes, which allows you to implement common appearance and navigation across your Web application and reuse presentation logic throughout the application.

There are two different patterns that address the implementation of controller classes for ASP.NET applications. The Page Controller assists you in building an application in which the navigation patterns are static but the pages are generated dynamically. For more complex applications where the navigation is dynamic or configurable based on a set of rules (e.g., user privileges or application state), the Front Controller allows for a more efficient implementation.

They are as follows:

Page controller:
Similar to Default asp.net controller .This would have a base page controller which will act like a master controller, will have all the events contained by an aspx.cs code behind page, but will contain logic for security verification , session managements,

The Front Controller pattern:
The Page Controller pattern becomes inefficient when you need to coordinate processing across multiple Web pages because of its implementation of a single object per logical page. The Front Controller is more efficient in such cases because it funnels all requests through a single controller and then directs requests through a single handler and a hierarchy of command classes. The handler retrieves parameters from the HTTP request, chooses the correct command, and transfers processing to it. After each command object performs the specified action, it can choose which view is required to render the page properly. Implementing the Front Controller results in more centralized application control because all page requests come through a single controller instead of being handled by different Page Controllers. But this can also be a liability if the handler does expensive processing, such as database lookups that could cause the entire application to operate slowly. The handler should be as efficient as possible and use external resources only when absolutely necessary. You should also consider caching any external resources to increase the handler’s performance.

You implement the Front Controller class by creating a Handler and a ActionFactory, which determines the necessary action using the request parameters (like action class name, query strings…etc) to execute in response to a request. ASP.NET provides the IHttpHandler interface to create custom interfaces required to service incoming HTTP requests.The Handler class would be implemented by inheriting from System.Web.IHttpHandler and adding the logic to instantiate and call the appropriate action from the ActionFactory. The ActionFactory defines a collection of actions and the logic that determines which of the actions should be executed. Calling the HandlerFactory returns the appropriate action object for which the Handler can call an Execute method (which will be the default method i.e if the action does not specify any method then Execute method would be called). Using this pattern, you can create more robust navigation scenarios and implement them centrally by extending the ActionFactory logic and creating additional actions to handle the required scenarios.
The type of action would be mapped with an Xml file. So every aspx page would have an action however multiple pages can have same action (reusability).
But this mapping would involve reflection, hence a performance issue (reflection being very expensive).

Handler/ HandlerFactory:
This module would be responsible for handling all requests through the pipe line and process it accordingly. Basically this would consist of a Handler class which will be inheriting from IHttpHandler interface. The ‘Process Request’ would be the method which will interpret a request and generate a suitable response. You will be rewriting/modifying the request through Http Context in this class.
This module would also take care of session validation and other user validation.

Action Factory:
This module would create/re-use action instances which will be retrieved by the request. These action instances would be cached. If an action does not figure in the cache then it will be created.
This module would map the request to generate an action instance. This would be done as a mapping through a xml file. The xml would be a config file which would house all action mappings.
Eg.
For a request

“\\SomeReleventUrl.aditi?action=releventaction&method=releventmethodname”
".aditi" - would invoke the respective handler class.

"releventaction" - would map to the xml config file and specify the action instance.

"Releventmethodname" - would specify the method to be invoked in the class. If not specified would take the default method.

Mapping in xml file:


<actionfactory>
<action name=” releventaction” type=”FullyQualifiedAcitonClassName” actionifSucess=”SomeReleventSuccessUrl” actionifError=”SomeReleventErrorUrl” >
</action>
<action name=” releventaction_one” type=”FullyQualifiedAciton_OneClassName”
actionifSucess=”SomeReleventSuccessUrl” actionifError=”SomeReleventErrorUrl” >
</action>
<action name=” releventaction_twotwo” type=”FullyQualifiedAciton_TwoClassName”
actionifSucess=”SomeReleventSuccessUrl” actionifError=”SomeReleventErrorUrl” >
</action>
<action name=” releventaction_three” type=”FullyQualifiedAciton_ThreeClassName”
actionifSucess=”SomeReleventSuccessUrl” actionifError=”SomeReleventErrorUrl” >
</action>
</actionfactory>

The type attribute would give the reference of the action class to be instantiated, which would bring reflection into play (hence a performance issue).But looking at the overall flexibility and scalability this can be tolerated.
actionifSucess attribute would specify the url to navigate in case the action returns as success.
actionifError attribute would specify the url to navigate in case the action returns an error or failed validation..

Using reflection we will invoke the Releventmethodname method in the action instance.
This would be the basic process flow for the entire incoming request.

Action: The action will interact with the ‘Model’ layer and will do all kind of data processing and logic implementation. This module would also interpret/recognize user inputs and translate into more generic data sources. All the user entered values would be retrieved though the request objects. The action would take context object as the parameter as it house both request and response objects.

Entity Objects: These can be either xml based objects or generic classes. These entity objects would store data and would be transferred across different layers.

State Management: Since performance is an issue, use of session would be discouraged unless of high necessity.
Caching to be implemented wherever possible.
ViewState to be made false by default for all the controls.
HttpContext would be used extensively to store value spanning through a single post cycle.

Code snippets:
Handler class
public class Handler : System.Web.IHttpHandler
{
///
/// Will process all request and send appropriate response
///
///
public void ProcessRequest(HttpContext context)
{
//Create an instance of Action Factory class
//Invoke CreateInstance of the Action Factory Class
//The Action Factory would return a URL as the response
//Navigate to the New URL
}
///
/// Whether the handler can be re used
///
public bool IsReusable
{
get
{
return true;
}
}
public Handler()
{
//
// TODO: Add constructor logic here
//
}
}
}

Action Factory
[Serializable]
public class ActionFactory
{
///
/// Translate the request parameter to intanstiate the action
/// and invoke the suitable method
///
///
public void CreateAcionInstance(HttpContext context)
{
//Translate the request params
//Use reflection to create an instance of action class
//Use reflection to invoke suitable method.
//Action class would return success or failure value .
//Translate the returned value as the new Url
//Transfering the new URl to Handler class
}
}

Action

[Serializable]
public class Action:IBaseActionClass
{
///
/// Translate the request parameter to intanstiate the action
/// and invoke the suitable method
///
///
public void ExecuteAcion(HttpContext context)
{
//Translate user inputs through request forms containted in //Httpcontext object
//Make Functions calls

//Use reflection to invoke suitable method.

//Action class would return success or failure as response.
}

}

IBaseActionClass would be an interface all action class would be inheriting from. Necessary for runtime castins of all the actions

Further logic and DB calls would be done in the “Model” layer.

The MVC architecture is released with framework 3.0, which will be integrated part of it.

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google
  • description
  • LinkedIn
  • Live
  • MySpace
  • Slashdot
  • Technorati
  • TwitThis
  • description
  • E-mail this story to a friend!
  • Print this article!

Tanmoy Biswas ASP.NET, Architecture & Design

  1. Nandita
    February 27th, 2008 at 16:32 | #1

    very usefull.
    thanks

  2. Prashanth
    February 28th, 2008 at 09:11 | #2

    Impressive, I was looking out for simlar design, Thanks Tanmoy good job.

  1. No trackbacks yet.