Pages

Tuesday 9 June 2009

Polymorphic Limitations in Strongly-Typed ASP.Net MVC Views

Strongly-typing your views gives you nice, easy access to what ever view model your controller passes to it. Simple and powerful.

Unfortunately, though, there are some limitations.

  1. Your View Model cannot be abstract.
  2. Your View Model will only get POSTed back as itself.

The first point is fairly simple. Everything works until you POST back your view model e.g.

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Update(MyAbstractViewModel model)
{
    // Clever bits go here...
}

Calling this action will result in the framework throwing a MissingMethodException: Cannot create an abstract class.

The second point is a little more complicated. Let's say you have 3 classes:

public abstract class MyAbstractViewModel
{
}

public class ViewModel1 : MyAbstractViewModel
{
}

public class ViewModel2 : MyAbstractViewModel
{
}

Now you create a simple GET Action that returns a View (strongly-typed to MyAbstractViewModel).

[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Index()
{
    MyAbstractViewModel model;

    if (something)
        model = new ViewModel1();
    else
        model = new ViewModel2();

    return View(model);
}


The view will render successfully. Unfortunately, our original POST Action will not receive either of the concrete classes - only the one the view is explicitly typed against (i.e. MyAbstractViewModel).

These are, obviously, not major issues but it does limit developers' creative freedom and the most elegant solution may have to be foregone in order to fit the framework.

No comments:

Post a Comment