我正在编写一段代码,该代码在每个网页上显示随机赞助商图像。我认为调用我的函数的最佳位置是在 Views/Shared/_Layout.cshtml 页面中,因为这是在每个页面上加载的页面。
我在域模型的服务类中编写了ChildActionOnly
函数,并在我的 homecontroller 中编写了一个函数,在 Views/Home/Randomsponsor.cshtml 中的简单视图中返回值,并在共享布局中使用 Html.action 调用该函数。
一切正常,但在运行时出现下一个错误:
{"The controller for path '/' was not found or does not implement IController."}
有谁知道如何解决这个问题?
领域项目中的方法:
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;
}
在 HomeController 中:
[HttpGet]
[ChildActionOnly]
public ActionResult RandomSponsor()
{
var model = service.advertsForCountry();
return PartialView("RandomSponsor", model);
}
Views/Home/ 中的简单视图:
@{
ViewBag.Title = "RandomSponsor";
}
@Html.Action("RandomSponsor")
我在 View/Shared/_Layout.cshtml 中的函数调用包含导航栏等:
@Html.Action("RandomSponsor", "HomeController")
问候。