2

Lets say I have two classes one base class:

public class BaseModel {

}

And a couple of children:

public class FooModel : BaseModel {

}

public class BarModel : BaseModel {

}

Now my view I would like to expect a model like this:

@model IList<BaseModel>

So that I can edit these models on one page.

However when I pass in a collection of these models in the action I get an exception saying:

The model item passed into the dictionary is of type 'System.Collections.Generic.List1[BarModel]', but this dictionary requires a model item of type 'System.Collections.Generic.IList1[BaseModel]'.

Like this:

var models = new List<BaseModel>(){ new BarModel(), new FooModel ()}
return View(models);

How can I achieve this?

Thanks

shenku
  • 11,969
  • 12
  • 64
  • 118
  • When serializing inherited classes you should look at http://stackoverflow.com/questions/20084/xml-serialization-and-inherited-types – Casperah Oct 28 '12 at 21:44

2 Answers2

2

Assuming you're not modify the model collection on the page, your page shouldn't take IList<T>. Rather it should take IEnumerable<T>:

@model IEnumerable<BaseModel>

That should take care of things.

Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
  • *facepalm*, can't believe. But why doesn't it work with the IList? – shenku Oct 28 '12 at 21:44
  • @shenku - Start here. There are 11 parts to the series. Obviously, it's a bit complicated to explain: http://blogs.msdn.com/b/ericlippert/archive/2007/10/16/covariance-and-contravariance-in-c-part-one.aspx – Justin Niessner Oct 28 '12 at 21:48
  • just a quick question, this works perfectly, for a post back though to the base type, is there a way i can then cast or try cast to an implementation type? thanks. – shenku Oct 28 '12 at 23:32
0

You can alseo use KnownType:

[Serilizable]
[KnownType(typeof(FooModel))]
[KnownType(typeof(BarModel))]
public class BaseModel 
{
} 

Hope this helps.

Casperah
  • 4,504
  • 1
  • 19
  • 13