I have an abstract class foo that contains some properties and methods. I have also have a number of classes that implement foo such as barfoo and foobar.
To safe rewriting the same code over multiple different views I’ve created a strongly typed partial view
@model List<foo>
@foreach (var x in Model) {
<div> x.SomeProperty </div>
}
Sadly, when I attempt to call this view with
@{ Html.RenderPartial("PartialView", List<Foobar>); }
I get the following error
The model item passed into the dictionary is of type System.Collections.Generic.List1[Namespace.Models.Foobar]', but this dictionary requires a model item of type 'System.Collections.Generic.List1[Namespace.Models.Foo]’.
Is what I’m trying to do possible at all or will I just have to duplicate code?
Trying exactly what you’re trying isn’t possible. If all you’re doing is enumerating over the collection (rather than modifying it), you could change to the following and things should be ok:
The problem is fairly easy to understand if you really think about it.
Your Model is a
List<foo>. That means that it should be entirely possible to sayModel.Add(new Barfoo());.You’re trying to pass a
List<Foobar>as the Model. Obviously,Model.Add(new Barfoo());would fail in that case because it’s not possible.Using a covariant interface like IEnumerable allows you to do exactly what you need.