Recently, Shaun Walker posted a blog in which he discussed whether DotNetNuke (DNN) should be rewritten in ASP.NET MVC. This blog created quite a stir, both within the DotNetNuke Community and within the ASP.NET Community as a whole.
In a comment that I added to Shaun’s post I suggested that the debate should not be over whether DNN should be rewritten in ASP.NET MVC (or any other framework that may come in the future), the discussion should be on “How can we enable developers to use the ASP.NET Technologies of their choice when developing extensions for DNN.” After all, if we rewrite DNN in MVC we effectively lock out WebForm developers.
Getting Started
Thanks to an idea from my son Andrew (much of what I used in this work was from his Maverick project on codeplex) I have been able the create a Framework that sits on top of DotNetNuke (and System.Web.MVC) and allows modules to be created using the ASP.NET MVC Framework (DotNetNuke.Web.Mvc).
In this article I will review how – using this add-on layer we can go about creating a simple ASP.NET MVC module. First, add an ASP.NET MVC Application to your Visual Studio solution.

Figure 1: Add a new MVC Web Application in the Desktop Modules folder called MVC_Test
Note that the location of the project is in the DesktopModules folder of our test website. This is exactly the same process we would use to add a WAP (Web Application Project) style module.
Before we go any further – we should prove to ourselves that this is a valid ASP.NET MVC Web Application, by selecting the Default.aspx file, and selecting View in Browser from the Context menu.

Figure 2: Browsing to the site demonstrates that this is a valid ASP.NET MVC Application
So now we have an MVC Application, how do we make it run as a Module in our DotNetNuke website? First we need to add a new class to our project – MVC_TestApplication.cs and we need to add references to our DotNetNuke Library project and to the new DotNetNuke.Web.Mvc project. When we have done that we need to open the new class we added and add some very simple code.
using System.Web.Routing;
using DotNetNuke.Web.Mvc;
using DotNetNuke.Web.Mvc.Routing;
namespace MVC_Test
{
public class MVC_TestApplication
: MvcModuleApplication
{
protected override string FolderPath
{ get { return "MVC_Test"; } }
protected override void Init()
{
base.Init();
RegisterRoutes(Routes);
}
private static void RegisterRoutes(RouteCollection
routes)
{
routes.RegisterDefaultRoute(
"MVC_Test.Controllers");
}
}
}
Listing 1: The MVC_TestApplication Class
The most important thing to note is that this class inherits from MvcModuleApplication, a new base class in the new DotNetNuke.Web.Mvc project. The Init method allows us to register any routes that our MVC Module Application will need and the FolderPath property tells the DotNetNuke.Web.Mvc project where our Views are located. Finally we need to make a very small change to the default View.
<%@ Page Language="C#"
MasterPageFile="../Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage" %>
<asp:Content ID="indexTitle"
ContentPlaceHolderID="TitleContent"
runat="server">
Home Page
</asp:Content>
<asp:Content ID="indexContent"
ContentPlaceHolderID="MainContent"
runat="server">
<h2><%= Html.Encode(ViewData["Message"]) %></h2>
<p>
To learn more about ASP.NET MVC visit
<a href=http://asp.net/mvc
title="ASP.NET MVC Website">
http://asp.net/mvc
</a>.
</p>
</asp:Content>
Listing 2: Index.aspx
If you blink you won’t see the change.
The change is to the reference to the MasterPageFile – the value of the attribute is changed from “~/Views/Shared/Site.Master” to “../Views/Shared/Site.Master”. The reference points to the same file – but the original reference assumes that the Views folder is at the root of the IIS Application – as a module it is actually at ~/DesktopModules/MVC_Test/Views”. By making the reference relative it will work in both scenarios.
Next we need to create our Module Extension. This is done in much the same way as we do today, the only difference being that when we register the Module Control we use the Namespace for the new class that we added – MVC_Test.MVC_TestApplication (See Figure 6 below). Since version 5.0, DNN has allowed module controls to be server controls and ultimately our new MVC_TestApplication class inherits from Control.

Figure 3: Add the MVC_TestApplication as the Source for the Default Module Control
Finally build our new MVC Module Application and copy the assembly from the bin folder of the project to the bin folder of the Website.
We are now ready to see if everything works. Add a new Page and add the newly registered Module to the Page and “hey presto” we get a Module that looks like the MVC Application.
The really cool thing is that we can still browse to the site (as an MVC Application) by selecting the Default.aspx page, and selecting View in Browser from the context menu, as we did in Figure 2 above.
What we got so far
In summary I have demonstrated so far, that using ASP.NET MVC for Module Development is a possibility. There still are a number of issues to resolve however, including, but not limited to:
1. Handling routes other than the default route.
2. Do the Html Helpers in ASP.NET MVC still work? and if not how can we make them work?
3. As Webforms allows only one Form tag which is defined in the base page -Default.aspx -how do we handle Forms in an MVC Module.
4. Issues around the use of Master pages and styles, and DNN skinning – we can solve this by removing the dependency on Master pages which is not a requirement of ASP.NET MVC.
I don’t expect any of these to be show-stoppers, but much more work still needs to be done.
The MvcModuleApplication Class
So far I described how I have developed a Framework that allows developers to create DotNetNuke (DNN) modules using the new ASP.NET MVC Framework. In this blog I will describe the new base class which is used to enable this ability - MvcModuleApplication.
Prior to DotNetNuke 5.0, all module controls had to be ASP.NET User Controls that inherited from PortalModuleBase – a base class in the DotNetNuke Web Application Framework that provided the context necessary for DotNetNuke’s Module Injection logic to load and inject the module control in the page. (Since about DNN 4.4 a module control was not required to be an ascx file – it could be a compiled server control, but it still had to inherit from PortalModuleBase and thus ultimately from UserControl).
IModuleControl
In DNN 5.0 an interface was introduced – IModuleControl – and the Module Injection logic was refactored to require the control to implement IModuleControl, rather than inherit from PortalModuleBase. PortalModuleBase itself was refactored to implement this interface so no existing modules were broken.
Creation of this interface means that it is no longer necessary to inherit from UserControl – although we are still required to ultimately inherit from the base class Control.
MvcModuleApplication
As demonstrated in Part 1 of this series, MVC Modules are required to include a class that inherits from MvcModuleApplication.
public class MVC_TestApplication : MvcModuleApplication
{
protected override string FolderPath
{
get { return "MVC_Test"; }
}
protected override void Init()
{
base.Init();
RegisterRoutes(Routes);
}
private static void RegisterRoutes(RouteCollection routes)
{
routes.RegisterDefaultRoute("MVC_Test.Controllers");
}
}
Listing 3: The MVC_TestApplication class
Listing 3 shows the class we added to the Test MVC module we created in the first part of this series. As discussed above, DotNetNuke Modules need to implement the interface IModuleControl and inherit from Control (this is necessary as the framework either needs to load a UserControl (ie ascx) or instantiate a Control and add it to the Controls collection of the Container. This is demonstrated in Listing 4, which partly shows the new base class – MvcModuleApplication - before we add any MVC Framework enabling code.
namespace DotNetNuke.Web.Mvc
{
public abstract class MvcModuleApplication : Control,
IModuleControl
{
#region IModuleControl Implementation
. . .
#endregion
}
}
Listing 4: The MvcModuleApplication class
Now that we have our base class, we can add the pieces to enable MVC modules. We are going to plug in to the ASP.NE Pipeline right at the beginning by implement logic similar to the ProcessRequest method of the MvcHandler.
protected internal virtual void ProcessRequest(HttpContextBase httpContext) {
AddVersionHeader(httpContext);
// Get the controller type
string controllerName = RequestContext.RouteData.GetRequiredString("controller");
// Instantiate the controller and call Execute
IControllerFactory factory = ControllerBuilder.GetControllerFactory();
IController controller = factory.CreateController(RequestContext, controllerName);
if (controller == null) {
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentUICulture,
MvcResources.ControllerBuilder_FactoryReturnedNull,
factory.GetType(),
controllerName));
}
try {
controller.Execute(RequestContext);
}
finally {
factory.ReleaseController(controller);
}
}
Listing 5: MvcHandler, ProcessRequest method
As the MvcModuleApplication class inherits from Control it is part of the WebForms Page Life Cycle. We will override the OnInit method which is our first opportunity to implement our own code (Listing 6).
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
//Wrap the http Context
HttpContextBase httpContext = new HttpContextWrapper(HttpContext.Current);
// Setup the module's context
ModuleRequestContext moduleRequestContext = new ModuleRequestContext
{
ModuleContext = ModuleContext,
ModuleRoutingUrl = "", // for now we will pass in an empty string
HttpContext = httpContext
};
_moduleResult = ExecuteRequest(moduleRequestContext);
}
Listing 6: MvcModuleApplication, OnInit
In this method we first create an instance of HttpContextBase – from the HttpContext. The MVC Framework uses this abstract base class to enable better testability, so we need to do the same.
Next, we create a ModuleRequestContext object. This class is a helper class that enables us to pass around the ModuleContext (from IModuleControl) a RoutingUrl and the HttpContext to any method that needs this information.
Finally we call the ExecuteRequest method, passing it this helper object and getting a ModuleRequestResult back.
public virtual ModuleRequestResult ExecuteRequest(ModuleRequestContext context) {
EnsureInitialized(context.HttpContext);
// Create a rewritten HttpRequest (wrapped in an HttpContext) to provide to the
//routing system
HttpContextBase rewrittenContext = new RewrittenHttpContext(context.HttpContext,
context.ModuleRoutingUrl);
// Route the request
RouteData routeData = GetRouteData(rewrittenContext);
// Setup request context
string controllerName = routeData.GetRequiredString("controller");
RequestContext requestContext = new RequestContext(context.HttpContext, routeData);
// Construct the controller using the ControllerFactory
IControllerFactory factory = ControllerBuilder.GetControllerFactory();
IController controller = factory.CreateController(requestContext, controllerName);
try {
// DotNetNuke Mvc Modules must implement IModuleController (not just IController)
// Because we need to retrieve the ActionResult without executing it, IController
// won't cut it so attempt to adapt the Controller if it does not directly
// implement IModuleController
IModuleController moduleController = controller as IModuleController;
if (moduleController == null)
{
moduleController = AdaptController(controller);
}
if (moduleController == null) {
throw new InvalidOperationException("Could not construct ModuleController");
}
// Execute the controller and capture the result
ActionResult result = moduleController.ResultOfLastExecute;
moduleController.Execute(requestContext);
// Return the final result
return new ModuleRequestResult {
ActionResult = result,
ControllerContext = moduleController.ControllerContext,
ModuleContext = context.ModuleContext
};
}
finally {
factory.ReleaseController(controller);
}
}
Listing 7: MvcModuleApplication, ExecuteRequest
The ExecuteRequest method (Listing 5) is very similar to the ProcessRequest method of MvcHandler, and so it should be as we need to do the same things, construct a Controller class and execute the Controller so it can Invoke the appropriate action. So lines 17 and 18 of Listing 7 are almost identical to lines 8 and 9 of Listing 5.
However there are a few differences.
- At the beginning of the method we do some setup work that is handled by other classes in the ASP.NET MVC Pipeline (lines 2-10).
- DotNetNuke MVC Modules must implement IModuleController (not just IController), so we attempt to cast the returner controller to IModuleController, and if that fails we attempt to adapt it (line 27)
- After we call the Execute method of Controller we then use the IModuleController’s "ResultOfLastExecute property to trap the ActionResult, which is returnedd by the Controller’s “action” method (lines 34-35).
- We generate a ModuleRequestResult to return to the caller code in OnInit (lines 38-42)
The important difference here is that unlike the main MVC Framework we need to trap the ActionResult. Two helper classes allow us to achieve this.
MvcControllerAdapter and ResultCapturingActionInvoker classes
public class MvcControllerAdapter : IModuleController
{
private Controller _adaptedController;
private ResultCapturingActionInvoker _actionInvoker;
public MvcControllerAdapter(Controller controller)
{
_adaptedController = controller;
_actionInvoker = new ResultCapturingActionInvoker();
_adaptedController.ActionInvoker = _actionInvoker;
}
public ActionResult ResultOfLastExecute
{
get { return _actionInvoker.ResultOfLastInvoke; }
}
public ControllerContext ControllerContext
{
get { return _adaptedController.ControllerContext; }
}
public void Execute(RequestContext requestContext)
{
if (_adaptedController.ActionInvoker != _actionInvoker)
{
throw new InvalidOperationException("Could not construct Controller");
}
((IController)_adaptedController).Execute(requestContext);
}
}
Listing 8 – The MvcControllerAdapter Class
The MvcControllerAdapter class (Listing 8) allows us to adapt standard MVC Framework Controller’s so that they implement the additional IModuleController interface. The main job of the MvcControllerAdapter is to replace the Controller’s ActionInvoker with a ResultCapturingActionInvoker. The ResultCapturingActionInvoker (Listing 9) captures the result of the Action and exposes it as the ResultofLastInvoke property.
public class ResultCapturingActionInvoker : ControllerActionInvoker
{
public ActionResult ResultOfLastInvoke { get; set; }
protected override void InvokeActionResult(ControllerContext controllerContext,
ActionResult actionResult)
{
// Do not invoke the action. Instead, store it for later retrieval
ResultOfLastInvoke = actionResult;
}
}
Listing 9: The ResultCapturingActionInvoker Class
So why do we need to capture the ActionResult?
In the standard MVC Pipeline the next phase after invoking the action is to render the View. DotNetNuke modules need to render their View inside the Container provided. The ExecuteRequest method of the MvcModuleApplication class returns the ModuleRequestResult (which contains the captured ActionResult) and saves it in a private variable.
Now, we need to remember that the MvcModuleApplication class inherits from the base Control class. DotNetNuke will have instantiated this class and added it to the Controls collection of the Container. We use this fact in the RenderControl method to render our View, by executing the ActionResult (which as long as a ViewResult was returned will render the View inside the Container). (see Listing 10)
public override void RenderControl(System.Web.UI.HtmlTextWriter writer)
{
if (_moduleResult != null)
{
//Execute the ActionResult
_moduleResult.ActionResult.ExecuteResult(_moduleResult.ControllerContext);
}
}
Listing 10 – MvcModuleApplication, RenderControl
And that’s how its done.
Conclusions
So in conclusion the process used to enable MVC modules to be created is as follows.
1. During the Init phase of the Page Lifecycle, mimic the MvcHandler to instantiate an MVC Controller class
2. Adapt the Controller to modify its ActionInvoker so we can capture the ActionResult from the Controller’s action method.
3. During the render phase of the Page LifeCycle, execute the returned ActionResult, to render the View.