Trying to use DisplayForModel in my ASP.NET MVC app but the models are not displaying

1.1k views Asked by At

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.

2

There are 2 answers

0
Andrew Stakhov On

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.

2
YavgenyP On

It is possible to create a display template for Cat/Dog, (unlike the interface, which cant be used for a template).

You do this by creating a Cat.cshtml file under Shared\DisplayTemplates folder, but in this template you will have to manualy set up the html you want this template to render.

EDIT As of your first question - I dont think DisplayForModel is what you're looking for, what you provbbaly need is DisplayFor