【问题标题】:ASP .Net Core Razor: Can't return ViewComponent from my PageModelASP .Net Core Razor:无法从我的 PageModel 返回 ViewComponent
【发布时间】:2018-10-25 01:39:33
【问题描述】:

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

不可调用的成员“ViewComponent”不能像方法一样使用。

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

【问题讨论】:

标签: razor asp.net-core


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2021-05-14
    • 1970-01-01
    • 1970-01-01
    • 2018-07-17
    • 2021-07-04
    • 1970-01-01
    • 1970-01-01
    • 2020-12-21
    • 2018-12-04
    相关资源
    最近更新 更多