M-V-VM in Asp.Net MVC : removing dependencies between asp.Net views and controller actions

Since the early days I have always been a fan of the ASP.net MVC framework, although I had one really big issue with it : the coupling of the controller actions in the view pages. This part was a real annoyance, since all the flow and logic was included in the controller, and none of it in the views, except the action flow; this was included in the views by using Html.ActionLink.

This has always been a nuisance for me, so last week, as I was working on a project, I decided to fix this issue…

IMHO the possible proceeding controller actions in the program flow should be defined in the controller action, and not in the view. So how could we do this, while still making it maintainable and easy to follow ?

After considering a few alternative routes, and thinking about it event more, it suddenly hit me; why not represent the possible routes as data.

A few development cycles later I had the following code in the controller:


public ActionResult Index()
{
     ViewData.Model = new VMIndex()
     {
         AllTasks = rTask.Find.OrderBy(o => o.Name),
         AL_AddTask = this.ActionLink(“Add new task”,c=>c.AddNewTask(null,null))
     };
     return View();
}

And this code in the view :


<h1>Task list</h1>
<%= Html.Grid(Model.AllTasks)
        .Columns(c=> {
            c.For(t => t.Name);
            c.For(t => t.Description);
            c.For(t => Html.ActionLink(t.AL_Status())).Named(“Status”).DoNotEncode();
            c.For(t => Html.ActionLink(t.AL_Edit())).Named(“Edit”).DoNotEncode();
            c.For(t => Html.ActionLink(t.AL_Delete())).Named(“Delete”).DoNotEncode();
        }).Empty(“No tasks yet”)
%>
<hr />
<h3>Add a new task</h3>
<% using (Html.BeginForm(Model.AL_AddTask)) { %>
    Name<br />
    <%=Html.TextBox(“Name”) %><br />
    Description<br />
    <%=Html.TextArea(“Description”) %><br />
    <%=Html.SubmitButton(Model.AL_AddTask) %><br />
<% }%>

Which looks rather nice in my opinion. Since I do not know whether I am the first person who thinks about this or not, I decided to publish the sourcecode together with an example on github.

The technical implementation is actually quite simple; I implement the Model-View-Viewmodel pattern, which is used in WPF, using a simple wrapper class for the action links (i.e. commands in MVVM). Once I made that link, the rest was childs play.

Next to this I also created some helper extensions, to make the code a little easier on the eyes.

I also think that by using this pattern we should be able to implement a winforms/WPF app using the same controller. Anybody who is willing to send me a git patch of a WPF application using this controller: please do !!!

PS: This also makes the actionlinks testable in an easy way; another responsibility that has been taken away from the view !!!

Bookmark and Share

comments powered by Disqus