私は、異なるグループの人々のリストを含むPersonListクラスを作成しました。私のコントローラでは、そのクラスをビューに渡します。私のビューは強く型付けされているので、私はそのクラスを参照しています。しかし私の見解では、そのグループのタイプ(学生、退職者、政治家)が必要なので、ビューの条件文でそれらを使用できます。私はPersonListクラスでグループごとに1つのオブジェクトを追加することでこの問題を解決しましたが、それを行うには最良の方法ではないと感じています。より良い解決策を私に指示してください。MVCの@modelスコープ外で宣言された型へのアクセス
.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>
は、カスタムメイドのビューモデルを作成し、コントローラにそのモデルを構成します。ビュー –