Razor ASP.Net核心剃须刀:Can';t从我的页面模型返回ViewComponent
我尝试使用Ajax调用Razor页面中的处理程序,该处理程序返回ViewComponent的结果,但是当我尝试下面的代码时,它会说: 非invocable成员“ViewComponent”不能像方法一样使用Razor ASP.Net核心剃须刀:Can';t从我的页面模型返回ViewComponent,razor,asp.net-core,Razor,Asp.net Core,我尝试使用Ajax调用Razor页面中的处理程序,该处理程序返回ViewComponent的结果,但是当我尝试下面的代码时,它会说: 非invocable成员“ViewComponent”不能像方法一样使用 使用MVC时,Controller基类包含一个ViewComponent方法,它只是一个帮助器方法,可以为您创建一个ViewComponentResult。这种方法在Razor Pages世界中还不存在,而是使用PageModel作为基类 解决此问题的一个选项是在PageModel类上创建一
使用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
};
}
}
public IActionResult OnGetPriceList()
{
return this.ViewComponent("PriceList", new { id = 5 });
}
除了它是一个扩展方法之外,上面的代码只是一个例子。为了使用它,您可以从现有的OnGetPriceList
(拼写错误修复)方法调用它,如下所示:
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
};
}
}
public IActionResult OnGetPriceList()
{
return this.ViewComponent("PriceList", new { id = 5 });
}
使它在这里工作的关键是使用this
,这将把它解析为扩展方法,而不是试图将构造函数作为方法调用
如果只使用一次,可以放弃扩展方法,只将代码本身嵌入到处理程序中。这完全取决于您-有些人可能更喜欢将扩展方法用于整个关注点分离论证。我发现了这个:它说创建扩展。那么在扩展中,我可以返回ViewComponent吗?