Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to invoke a View Component from controller

Is it possible to invoke a View Component from controller and render it to a string? I am really looking for some code example for this. Any help will be much appreciated.

like image 277
eadam Avatar asked Jan 18 '15 11:01

eadam


People also ask

How do I invoke a view component?

Invoke a view component directly from a controller View components are typically invoked from a view, but they can be invoked directly from a controller method. While view components don't define endpoints like controllers, a controller action that returns the content of a ViewComponentResult can be implemented.


1 Answers

As of beta7 it is now possible to return a ViewComponent directly from a controller. Check the MVC/Razor section of the announcement

The new ViewComponentResult in MVC makes it easy to return the result of a ViewComponent from an action. This allows you to easily expose the logic of a ViewComponent as a standalone endpoint.

So now the code for returning the sample view component just needs to be:

public class HomeController : Controller
{
    public IActionResult Index()
    {
        return ViewComponent("My");
    }
}
like image 151
Daniel J.G. Avatar answered Oct 07 '22 11:10

Daniel J.G.