Ich habe eine PersonList-Klasse erstellt, die Listen verschiedener Völkergruppen enthält. In meinem Controller werde ich diese Klasse zur Ansicht weitergeben. Meine Sicht ist stark typisiert, daher verweise ich auf diese Klasse. Aber meine Ansicht erfordert Typen dieser Gruppen (Student, Retired, Politic), damit ich sie in der bedingten Anweisung in View verwenden kann. Ich löste dieses Problem, indem ich ein Objekt pro Gruppe in der PersonList-Klasse hinzufügte, aber ich denke, das ist nicht der beste Weg, dies zu tun. Bitte leiten Sie mich zu einer besseren Lösung.Zugriff auf außerhalb von @model deklarierten Typen in MVC
.cs file
public interface IPerson
{
}
public abstract class Person
{
public string Name { get; set; }
public string LastName { get; set; }
public Int16 Age { get; set; }
}
public class Politics : Person, IPerson
{
public string Party { get; set; }
public int Experience { get; set; }
}
public class Students : Person, IPerson
{
public string Major { get; set; }
public int Year { get; set; }
}
public class Retired: Person, IPerson
{
public int Pension { get; set; }
public string Hobby { get; set; }
}
public class PersonLists : IPerson
{
public List<Retired> AllRetired = new List<Retired>();
public List<IPerson> AllPeople = new List<IPerson>();
public Students AStudent = new Students();
public Politics APolitic = new Politics();
public Retired ARetired = new Retired();
}
cshtml file:
@model ConferenceAttendees.Models.PersonLists
<style>
h6 {
display: inline
}
th{
text-align:center;
}
</style>
<div>
<table style="width:100%" align="left">
<tr>
<th>Imie</th>
<th>Nazwisko</th>
<th>Wiek</th>
<th>Partia</th>
<th>Doswiadczenie</th>
<th>Kierunek</th>
<th>Rok</th>
</tr>
@foreach (dynamic item in Model.AllPeople)
{
<tr>
<th>@item.Name</th>
<th>@item.LastName</th>
<th>@item.Age</th>
@if (item.GetType() == Model.APolitic.GetType())
{
<th>@item.Party</th>
<th>@item.Experience</th>
<th>b.d</th>
<th>b.d</th>
}
@if (item.GetType() == Model.AStudent.GetType())
{
<th>b.d</th>
<th>b.d</th>
<th>@item.Major</th>
<th>@item.Year</th>
}
</tr>
}
</table>
</div>
erstellen Maß Ansicht-Modell und komponieren, dieses Modell in der Steuerung. Entfernen Sie die @if-Anweisungen aus der Sicht –