使用 MVC 时,Controller 基类包含一个 ViewComponent方法,它只是一个帮助方法,它为您创建一个 ViewComponentResult。 Razor Pages 世界中尚不存在此方法,而是使用 PageModel 作为基类。
解决此问题的一种方法是在 PageModel 类上创建一个扩展方法,如下所示:
public static class PageModelExtensions
{
public static ViewComponentResult ViewComponent(this PageModel pageModel, string componentName, object arguments)
{
return new ViewComponentResult
{
ViewComponentName = componentName,
Arguments = arguments,
ViewData = pageModel.ViewData,
TempData = pageModel.TempData
};
}
}
除了它是一个扩展方法之外,上面的代码只是ripped out of Controller。为了使用它,您可以从现有的OnGetPriceList(错字已修复)方法中调用它,如下所示:
public IActionResult OnGetPriceList()
{
return this.ViewComponent("PriceList", new { id = 5 });
}
让它在这里工作的关键是使用this,它将它解析为扩展方法,而不是尝试将构造函数作为方法调用。
如果您只打算使用这个一次,您可以放弃扩展方法,而只是将代码本身嵌入到您的处理程序中。这完全取决于您 - 有些人可能更喜欢扩展方法来解决整个关注点分离的论点。