MVC - Create a typed model being a generic list

2

I would like to create a typed Model with it being a list of type T .

Using: ASP.NET MVC 5 Razor
For example: My model in cshtml will look like this:

@model List<T>

@foreach (var item in Model)
{
    <h1>@item.name</h2>
}

Is it possible?

    
asked by anonymous 23.06.2017 / 03:03

1 answer

8

Use Interfaces

Look, your View expects to receive a list of objects, but they do not necessarily have the Name property:

@foreach (var item in Model)
{
    <h1>@item.name</h2>
}

So we have created a contract to make it clear to these objects that they are required to implement this property, which also View that any object on that list will have a Name property.

public interface ITemQueTerPropName
{
    string Name { get; set; }
}

Now warns this to your View, so it will behave as expected:

@model List<ITemQueTerPropName>

@foreach (var item in Model)
{
    <h1>@item.Name</h2>
}

And do not forget to implement the interface on the relevant objects:

public class UmObjetoQueIraAparecerNaView : ITemQueTerPropName
{
    public string Name { get; set; }
}

So your View will behave as expected, and will also ensure that your view will only render objects that have the Name property.

    
23.06.2017 / 09:01