MVC - Creating a typed model as a generic list

Asked

Viewed 734 times

2

I would like to create a typed model being a list of the type T.

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

@model List<T>

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

It is possible?

  • The way you did not... What’s the point of this?

  • But is there any way to get this result? Probably not?

  • Goal is to use it as partial view... which will list the object of the list. (Independent of the type of the list)

  • Bruno to View needs to know the type you are sending, that way a View with the Generic type would not give... only if it were a View with the same fields

  • @Brunoheringer you want to create a partial view to save 5 lines of code??

  • @LINQ think he wants to save on files cshtml.

Show 1 more comment

1 answer

8


Use Interfaces

Check it out, your View expects to receive a list of objects where they necessarily have the property Name:

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

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

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

Now tell this to your View, so she will behave as expected:

@model List<ITemQueTerPropName>

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

And don’t forget to implement the interface in the relevant objects:

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

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

  • Just to let you know that in the third code block, you opened a <H1> tag and closed with </H2>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.