s you saw in the first article in this series, ASP.NET automatically implements the Model-View-Presenter (MVP) pattern when you use the built-in “code-behind” approach. However other patterns, usually referred to as “controller patterns,” are also suitable for use in ASP.NET. These patterns extend the capability for displaying a single view by allowing applications to choose which view to display at runtime depending (usually) on user interaction.
The Use Case Controller Pattern
The Use Case Controller pattern coordinates and sequences interaction between the system and its users to carry out a specific process. The “Wizard” interface style is an example; users step through a sequence of screens in a defined order. They may be able to go backwards as well as forwards, or jump to a specific step, but the overall approach suggests a defined “forward movement” through the process (see Figure 1).
![]() |
? |
Figure 1. The Use Case Controller Pattern: The diagram shows flow control in a typical Wizard-style interaction. |
In this pattern, a single Controller interacts with the Model (the data) and displays the appropriate view, depending on the user’s interaction or the application’s requirements. It is possible to incorporate multiple Controllers in a hierarchy for complex processes, and use configuration files or other persisted data to define the steps, which lets you alter control flow without recompiling and redeploying the application for easy maintenance and extension or alteration of the overall process. However, the underlying principles are as shown in Figure 1.
The Page Controller and Front Controller Patterns
![]() |
? |
Figure 2. The Page Controller and Front Controller Patterns: These patterns are well-suited to ASP.NET, because they support partial or alternate views. |
Two other design patterns related to Use Case Controller are the Page Controller and Front Controller patterns. These implement and extend the principles of the Use Case Controller pattern in a way that specifically suits ASP.NET. These patterns allow an application to either select the content to display in a page using different partial Views, such as varying page content composition with common headers and footers, or select which View (page) to display, such as pages that present different content depending on the browser or user credentials (see Figure 2).
The Page Controller pattern uses a single Presenter (part of the MVP pattern implemented by the ASP.NET code-behind technology), which interacts with the Model (the data for the page). When it receives a request, the Page Controller can determine which partial View to display within the page, and then interact with that View following the MVP pattern.
In the Front Controller pattern, a separate controller examines each request and determines which page to display. Each page is a complete MVP implementation with its own View, and each Presenter interacts with the View and the Model (the data).
The Plug-in, Module, and Intercepting Filter Patterns
A series of related design patterns define how applications can use additional components or modules to extend their capabilities or perform specific functions. Typically, they allow the features or behavior of an application to change when it loads separate components that implement extra functionality
The Plug-in pattern usually relates to general-purpose software components. For examples, consider the way that Web browsers use ActiveX controls, Java applets, and the Macromedia plug-in to provide extra functionality or display Flash animations.
The Module pattern usually relates to the capability of an application to load and use custom assemblies (modules) that extend its functionality. An example is the Composite UI Application Block (CAB), which contains a feature that allows an application to load a complete interface component (such as a window with its associated Controller or Presenter and data), and integrate it seamlessly into a composite Windows Forms interface.
The Intercepting Filter pattern has a slightly different implementation. It usually consists of a component that resides within an application pipeline, such as the HTTP pipeline that ASP.NET uses to process each request. The framework calls a method within the HTTP module at a specific point during pipeline processing, allowing the module to change the behavior of the application.
Implementing the Controller Patterns in ASP.NET
You can implement both the Page Controller and the Front Controller patterns in ASP.NET. In fact, ASP.NET makes it easy to combine them if required, as shown in Figure 3.
![]() |
? |
Figure 3. Combining Front Controller and Page Controller: The diagram shows how the Page Controller and Front Controller patterns can work in combination. |
In Figure 3, the Front Controller specifies which of three Web pages will load depending on some feature of the request. Each Web page implements the MVP pattern, though one of them also uses the Page Controller pattern to determine which partial View to display within its page. This is, in fact, the overall structure of the downloadable sample application.
All three patterns implemented in this article, the Use Case Controller, Page Controller, and Front Controller, make use of the same set of three partial Views implemented as user controls. Therefore, before looking at the pattern implementations in detail, the next section examines these three user controls.
Implementing the Three Partial View User Controls
To illustrate the various controller patterns, the example application uses three very simple user controls that implement Views for several of the pages. Figure 4 shows the page from the Use Case Controller pattern example that uses the CustomerList user control (CustomerList.ascx). Note that the page heading, buttons, and actual URL are part of the hosting page, and not part of the user control.
![]() |
? |
Figure 4. The Customer List User Control: In this figure, the Customer List user control doesn’t include the page heading, the buttons, or the “Actual URL” label. |
The View itself (the ASPX page) contains only a GridView control and a Label control (where any errors messages will appear). The code to populate the GridView is in the Page_Load event handler. It uses the CustomerModel class to get a DataSet containing the list of customers and binds the DataSet to the GridView to show the results:
public partial class CustomerList : System.Web.UI.UserControl { protected void Page_Load(object sender, EventArgs e) { try { // get DataSet of customers from CustomerModel class // and bind to GridView control in the page CustomerModel customerList = new CustomerModel(); GridView1.DataSource = customerList.GetCustomerList(); GridView1.DataBind(); } catch (Exception ex) { Label1.Text += "USER CONTROL ERROR: " + ex.Message; } Label1.Text += ""; } }
![]() |
? |
Figure 5. The Customer Details User Control: Here’s how the control looks in the example application. |
The second user control, named “CustomerDetails” (CustomerDetails.ascx), displays details of a specific customer (see Figure 5). To simplify the example, this is hard-coded to show the details of the customer with ID value “ALFKI”, but you could of course easily modify the page to allow users to enter a customer ID in the same way as in the Default.aspx page you saw earlier.
The code in the Page_Load event handler of this user control uses the GetCustomerDetails method of the CustomerModel class to get a DataRow containing details of the specified customer, converts this to an Object array, and then iterates through the array displaying the values:
public partial class CustomerDetails : System.Web.UI.UserControl { protected void Page_Load(object sender, EventArgs e) { try { // use CustomerModel to get DataRow // for specified customer CustomerModel customers = new CustomerModel(); DataRow[] details = customers.GetCustomerDetails("ALFKI"); // convert row values into an array Object[] values = details[0].ItemArray; Label1.Text += "Customer Details from " + "CustomerModel class:
"; // iterate through the array displaying the values foreach (Object item in values) { Label1.Text += item.ToString() + ", "; } } catch (Exception ex) { Label1.Text += "USER CONTROL ERROR: " + ex.Message; }
? Figure 6. The City List User Control: The City List user control displays a list of cities where customers reside, shown here in the sample application.
Label1.Text += ""; } }
The third user control, named “CityList” (CityList.ascx), displays a list of the cities where customers reside, together with a count of the number of customers in each city (see Figure 6).
The code in the Page_Load event handler of the “CityList” user control uses the CustomerModel.GetCityList method to get a System.Collections.SortedList instance containing the list of cities and the count of customers in each one. It then iterates through the list displaying the key (the city name) and the value (the number of customers) for each item:
public partial class CityList : System.Web.UI.UserControl { protected void Page_Load(object sender, EventArgs e) { try { // use CustomerModel to get SortedList of cities CustomerModel customers = new CustomerModel(); SortedList cities = customers.GetCityList(); // iterate through the SortedList displaying // the values Label1.Text += "List of cities from CustomerModel class:
"; foreach (String key in cities.Keys) { Label1.Text += key + " (" + cities[key].ToString() + ")
"; } } catch (Exception ex) { Label1.Text += "USER CONTROL ERROR: " + ex.Message; } Label1.Text += ""; } }
Implementing the Use Case Controller Pattern
The example implementation of the Use Case Controller pattern uses a single ASPX page (TransferPage1.aspx), with a code-behind file that implements the Presenter. If the page load was caused by a postback (a user clicked one of the buttons in the page), code in the Page_Load event of the Presenter extracts the name of the partial View (the user control) to display from the page’s ViewState, and saves this in a local variable named viewName. When the page load is not a postback, the code just sets viewName to the default value “CustomerList” and calls the method LoadAndDisplayView within the Presenter:
public partial class TransferPage1 : System.Web.UI.Page { String viewName = String.Empty; protected void Page_Load(object sender, EventArgs e) { if (Page.IsPostBack) { // get current view name from page viewstate viewName = (String)ViewState["ViewName"]; } else { viewName = "CustomerList"; LoadAndDisplayView(); } // display actual URL of currently executing page lblActualPath.Text = Request.CurrentExecutionFilePath; String qs = Request.QueryString.ToString(); if (qs != null && qs != String.Empty) { lblActualPath.Text += '?' + qs; } } ...
The remaining code in the Page_Load event displays the actual URL of the current page and any query string, so that you can see the effects of the Front Controller when it redirects requests to different pages. You will see how the Front Controller works in the next article in this series.
To load and display a user control dynamically, code in the LoadAndDisplayView method creates a new instance of the control and then adds it to the Controls collection of an ASP.NET Placeholder control located in the main View (the ASPX page). After displaying the user control, the code sets the Enabled properties of the “Back” and “Next” buttons, depending on the current view name, and displays the name of the view in the page header element (a
private void LoadAndDisplayView() { // load and display the appropriate view if (viewName != null && viewName != String.Empty) { try { UserControl view = (UserControl)LoadControl(viewName + ".ascx"); viewPlaceHolder.Controls.Add(view); } catch (Exception ex) { throw new Exception( "Cannot load view '" + viewName + "'", ex); } } else { viewName = "No view specified"; } // set state of buttons to match view btn_Back.Enabled = (viewName != "CustomerList"); btn_Next.Enabled = (viewName != "CityList"); // display name of current view pageHeaderElement.InnerText = "Current View is '" + viewName + "'"; // save in page viewstate for use in postback ViewState["ViewName"] = viewName; }
As an alternative, you could use the Server.Execute method to execute separate ASPX pages, each an MVP pattern implementation with its own Presenter (code-behind file) and View (ASPX page) that generates the appropriate output. This output will appear in the resulting page as a partial View, though you must remember not to include the , , and elements in the partial View implementation.
However, it is likely that you will have to include the ASP.NET


What We Should Expect from Cell Phone Tech in the Near Future
The earliest cell phones included boxy designs full of buttons and antennas, and they only made calls. Needless to say, we’ve come a long way from those classic brick phones


The Best Mechanical Keyboards For Programmers: Where To Find Them
When it comes to programming, a good mechanical keyboard can make all the difference. Naturally, you would want one of the best mechanical keyboards for programmers. But with so many


The Digital Panopticon: Is Big Brother Always Watching Us Online?
In the age of digital transformation, the internet has become a ubiquitous part of our lives. From socializing, shopping, and learning to more sensitive activities such as banking and healthcare,


Embracing Change: How AI Is Revolutionizing the Developer’s Role
The world of software development is changing drastically with the introduction of Artificial Intelligence and Machine Learning technologies. In the past, software developers were in charge of the entire development


The Benefits of Using XDR Solutions
Cybercriminals constantly adapt their strategies, developing newer, more powerful, and intelligent ways to attack your network. Since security professionals must innovate as well, more conventional endpoint detection solutions have evolved


How AI is Revolutionizing Fraud Detection
Artificial intelligence – commonly known as AI – means a form of technology with multiple uses. As a result, it has become extremely valuable to a number of businesses across


Companies Leading AI Innovation in 2023
Artificial intelligence (AI) has been transforming industries and revolutionizing business operations. AI’s potential to enhance efficiency and productivity has become crucial to many businesses. As we move into 2023, several


Step-by-Step Guide to Properly Copyright Your Website
Creating a website is not easy, but protecting your website is equally important. Implementing copyright laws ensures that the substance of your website remains secure and sheltered. Copyrighting your website


Fivetran Pricing Explained
One of the biggest trends of the 21st century is the massive surge in analytics. Analytics is the process of utilizing data to drive future decision-making. With so much of


Kubernetes Logging: What You Need to Know
Kubernetes from Google is one of the most popular open-source and free container management solutions made to make managing and deploying applications easier. It has a solid architecture that makes


Why Is Ransomware Such a Major Threat?
One of the most significant cyber threats faced by modern organizations is a ransomware attack. Ransomware attacks have grown in both sophistication and frequency over the past few years, forcing


Tools You Need to Make a Data Dictionary
Data dictionaries are crucial for organizations of all sizes that deal with large amounts of data. they are centralized repositories of all the data in organizations, including metadata such as