我正在開發一個mvc項目,我想在每個頁面上顯示一個sponsorimage。在視圖中調用靜態函數mvc
但是我很難將它們顯示到每個視圖上呈現的共享佈局頁面中。
我在我的域服務類中創建了一個函數,在那裏我搜索學生的學校,因爲學校與一個國家相關,而不是學生。 當我得到那個countryId時,我通過每個Advert的國家搜索countryId等於該學校countryId的國家。在這種情況下,我尋找該特定廣告的贊助商,將它們放入贊助商列表中,從該贊助商列表中選擇一個隨機贊助商,並返回贊助商公司(因爲我將每個贊助商圖片更名爲公司名稱)。
現在我想把這個功能調用到共享的佈局中,所以每次頁面渲染時,都會爲該特定的學生顯示一個隨機的主辦者圖片。但我不知道如何調用該函數,因爲共享佈局沒有控制器類。
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;
}
對不起,英語不是我的母語。
考慮製作一個兒童動作。 – SLaks
我的建議會忘記'靜態方法',因爲它不是一個正確的'MVC'模式,商業模型的邏輯不應該在'View'中。 創建一個'ViewModel',然後返回一個簡單的'PartialView'綁定到'ViewModel'。 – IamStalker