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.