S'Ok, Given the following model :-
public class SomeViewModel
{
public IAnimal Animal { get; set; }
public Exception Exception { get; set; }
}
and an IAnimal
can be either this..
public class Cat : IAnimal { .. }
public class Dog : IAnimal { .. }
and give the following Razor code
.. snip ..
@if (Model.Animal!= null)
{
Html.DisplayForModel(Model.Animal);
}
else if (Model.Exception != null)
{
Html.DisplayForModel(Model.Exception);
}
@Html.ActionLink("Lets go back home.", "Index")
the view is not rending the properties of a cat or dog .. if the model instance is one of those.
Right now each of these models are just a few strings and bools, etc. All primitive types.
So I thought that, if I just pass in the model, it should be rendered.
Anyone have any suggestions to what I might have done, wrong?
Also - for bonus points, is is possible to create a display template for one of those two classes - let's say the Cat
class - and have it just display instelf? eg. tell it to display itself, instead of me manually creating to Html.Label
... etc.
Keep in mind that working with interfaces is somewhat of a pain if you're relying on metadata annotations to allow autorendering in the view (things like property captions, validation, etc). MVC engine will try to extract metadata from interface and not the concrete type, at least that's what it does using built in templates. You can override the templates to get around this limitation by examining the concrete type and loading metadata based on its type. It's doable, but I don't recommend it as there's a performance hit.