私は mvc プロジェクトに取り組んでおり、各ページにスポンサー画像を表示したいと考えています。
しかし、各ビューでレンダリングされる共有レイアウト ページにそれらを表示するのに苦労しています。
学校は学生ではなく国にリンクされているため、学生の学校を検索するドメインサービスクラスに関数を作成しました。そのcountryIdを取得したら、countryIdが学校のcountryIdと等しい各Advertの国を検索します。その場合、その特定の広告のスポンサーを探し、SponsorList に入れ、その SponsorList からランダムなスポンサーを選択し、SponsorCompany を返します (各スポンサー画像の名前を会社名に変更したため)。
ここで、その関数を共有レイアウトに呼び出したいので、ページがレンダリングされるたびに、その特定の学生のスポンサー画像がランダムに表示されます。しかし、共有レイアウトにはコントローラークラスがないため、その関数を呼び出す方法がわかりません。
public String advertsForCountry()
{
String studentSchool = finder.getLoggedStudent().SchoolId;
int studentCountry = db.Schools.Find(studentSchool).CountryId;
List<Sponsor> sponsorsForStudent = new List<Sponsor>();
List<Advert> adverts = db.Adverts.ToList();
foreach(Advert adv in adverts)
{
foreach(Country cntry in adv.Countries)
{
if(cntry.CountryId == studentCountry)
{
sponsorsForStudent.Add(adv.Sponsor);
}
}
}
Random random = new Random();
int randomSP = random.Next(0, sponsorsForStudent.Count()-1);
string sponsorAdvert = sponsorsForStudent.ElementAt(randomSP).SponsorCompany;
return sponsorAdvert;
}
申し訳ありませんが、英語は私の母国語ではありません。