gpt4 book ai didi

razor - ASP .Net 核心 Razor : Can't return ViewComponent from my PageModel

转载 作者:行者123 更新时间:2023-12-05 04:04:12 25 4
gpt4 key购买 nike

我正在尝试使用 Ajax 调用我的 Razor 页面中的处理程序,该处理程序返回 ViewComponent 的结果,但是当我尝试下面的代码时,它说:

Non-invocable member "ViewComponent" cannot be used like a method.

public IActionResult OnGetPriceist()
{
return ViewComponent("PriceList", new { id= 5 });
}

最佳答案

使用 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,它将把它解析为扩展方法,而不是试图将构造函数作为方法调用。

如果您只打算使用这个一次,您可以放弃扩展方法,而只是将代码本身嵌入到您的处理程序中。这完全取决于您 - 对于整个关注点分离论点,有些人可能更喜欢扩展方法。

关于razor - ASP .Net 核心 Razor : Can't return ViewComponent from my PageModel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52974270/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com