Polymorphic Limitations in Strongly-Typed ASP.Net MVC Views

09 Jun

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.

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).

public ActionResult Index()
    MyAbstractViewModel model;

    if (something)
        model = new ViewModel1();
        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.

Leave a comment

Posted by on June 9, 2009 in ASP.Net MVC



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: