2013-06-03 21 views
0

我正在開發一個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;  
} 

對不起,英語不是我的母語。

+0

考慮製作一個兒童動作。 – SLaks

+0

我的建議會忘記'靜態方法',因爲它不是一個正確的'MVC'模式,商業模型的邏輯不應該在'View'中。 創建一個'ViewModel',然後返回一個簡單的'PartialView'綁定到'ViewModel'。 – IamStalker

回答

0

要擴展@SLaks的建議;

創建一個標記爲ChildActionOnlyAttribute的動作(這可防止通過常規HTTP請求調用該動作)。下面是從我的網站的例子:

[HttpGet] 
[ChildActionOnly] 
public ActionResult RandomQuote() 
{ 
    var model = _services.GetRandomQuote(); 

    return PartialView("_QuoteOfTheMomentWidget", model); 
} 

這孩子動作被通過簡單的@Html.Action("randomquote")堪稱_Layout

+0

但是在哪個控制器中放置代碼?因爲_Layout.cshtml沒有控制器。 – Gijs

+0

@Gijs任何控制器都可以工作。例如,我發佈的假設操作是在主控制器中定義的,並且'_QuoteOfTheMoment.cshtml'視圖存在於'home'或'shared'文件夾中。如果它在'WidgetsController'中,則調用被調整爲'@ Html.Action(「randomquote」,「widgets」)'。 –

+0

我正在實施您的解決方案,但得到錯誤 '{「沒有找到路徑'/'的控制器,或者沒有實現IController。」}'我以爲我在這裏找到了解決方案: http://stackoverflow.com/questions/14011026/the-controller-for-path-was-not-found-or-does-not-implement-icontroller 但是我沒有使用這些區域,這個功能必須爲每個人工作。 – Gijs

0

創建一個返回部分視圖的控制器操作。

public PartialViewResult SponsoredAdvert() 
{ 
    var model = new SponsoredAdverModel(); 
    model.AdvertText = _domainService.advertsForCountry(); 
    return PartialView("myView", model); 
} 

放置在一個合適的控制器方法(HomeController將使考慮到這是你的Layout.cshtml感),並在您的視圖中使用RenderAction

@Html.RenderAction("MyAction", "MyController") 

正如你所看到的,RenderAction允許你到指定了這個控制器,這意味着你可以在你的Layout.cshtml中使用它,即使它本身並沒有與特定的控制器關聯。

+0

我沒有在homecontroller視圖中調用該方法,而是在共享的_layout.cshtm視圖中調用該方法。這包含我的導航欄等,並沒有控制器。如果我把它放在homecontroller中,這隻會在主頁上工作。 – Gijs

+0

不,它不會。正如我在我的回答中所描述的那樣,'RenderAction'帶有'controller'參數,它允許您指定哪個控制器類包含操作方法'MyAction'。您可以使用它將來自任何控制器的PartialViewResults渲染到任何視圖中 - 包括來自Layout.cshtml。 –