ASP .Net Core Razor: Can't return ViewComponent from my PageModel

Viewed 789

I am trying to use Ajax to call a handler in my Razor page that returns the result of a ViewComponent, however when I try the code below, it says:

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

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

When using MVC, the Controller base class includes a ViewComponent method, which is just a helper method that creates a ViewComponentResult for you. This method does not yet exist in the Razor Pages world, where instead you use PageModel as the base class.

One option to work around this is to create an extension method on the PageModel class, that would look something like this:

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
        };
    }
}

Apart from it being an extension method, the code above is just ripped out of Controller. In order to use it, you can call it from your existing OnGetPriceList (typo fixed) method, like this:

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

The key to making it work here is to use this, which will resolve it to the extension method, rather than trying to invoke the constructor as a method.

If you're only going to use this once, you could forego the extension method and just embed the code itself inside of your handler. That's entirely up to you - some people might prefer the extension method for the whole separation-of-concerns argument.

Related