Kyle
Kyle

Reputation: 1172

ASP.NET MVC Display Template for Generic Type

I am trying to use the model ListModel as a generic list model. I would like to enter on the page

@Html.DisplayForModel()

However the MVC is not correctly finding the templated file "ListModel.cshtml". It must work differently for generic models. What should I name the templated file in order for it to correctly be located?

public class ListModel<T>
{
public IEnumerable<T> Models { get; set; }
public string NextPage { get; set; }
}

I would expect it to look for Shared/DisplayTemplates/ListModel.ascx but it doesn't. Does anyone know?

Edit:

I did end up solving this by simply removing the generic parameter like so. I do want to know if you can still have a generic file name though.

public class ListModel
{
    public IEnumerable Models {get;set;}
    public string NextPage {get;set;}
}

Upvotes: 4

Views: 3597

Answers (3)

Chris F Carroll
Chris F Carroll

Reputation: 12360

You can explicitly specify your Template, then MVC will find it as usual.

@Html.DisplayForModel("ListModel")

and similarly

@Html.DisplayFor(m=>m.AProperty,"TemplateName")

Upvotes: 0

Derek Morrison
Derek Morrison

Reputation: 5574

As a workaround, could you decorate the ListModel<T> class with the UIHint attribute to force it to use the template you want?

For example,

[UIHint("ListModel")]
public class ListModel<T>
{
...

Upvotes: 2

corvuscorax
corvuscorax

Reputation: 5930

I don't think this is possible.

Think about it: If you somehow was able to declare the template as generic (say by calling it ListModel`1.ascx or something) how would the MVC runtime handle any specific instances of the model? And how would you display the generic properties/fields in the template?

I haven't been able to find a place where MS specifically states that generic models are disallowed, but I can't see how they would make it work.

This is also supported by the observation that if you try to create a strongly-typed view, then generic classes are filtered out of the drop-down box.

Upvotes: 2

Related Questions