1

I made a component:

public class CatSearchComponent : ViewComponent
{
    public async Task<IViewComponentResult> InvokeAsync()
    {
        return View();
    }
}

@await Component.InvokeAsync("CatSearchComponent")

Within the component I have a button that I want to use jquery $.ajax to call a method and render some data within the component, e.g. an action called GetCats() that returns some Json data.

It would be nice to put this method into the component since it's component specific.

However I am not sure what the url would be to put into my $.ajax call to call such a method, or even if it's allowed in MVC.

I could create a new controller and put an action on it to get the data but it would be nice if it was coupled with my ViewComponent. Is there a way to do this?

NibblyPig
  • 51,118
  • 72
  • 200
  • 356
  • I don't think it is doable. I don't see any workaround except using controllers in mvc pattern. – ibubi May 29 '19 at 11:51
  • 1
    No. Think of a view component as simply a way to wrap some complex logic around a partial. It's not a thing that continues to exist or that is reactive to requests like a controller; it's instantiated during the view rendering and then dumped afterwards. – Chris Pratt May 29 '19 at 14:41
  • 1
    I really can't see the point of view components at all, you may as well simply create a controller I think. Unless there's some advantage I am missing, it's like a controller that forces you to have only 1 method – NibblyPig May 29 '19 at 15:18

1 Answers1

0

You can, as it happens, but not directly.

You can create an ActionResult in an MVC Controller, which returns the ViewComponent result; then, in JavaScript/jQuery, call the Controller.

See this StackOverflow answer for a full description and code:

Viewcomponent alternative for ajax refresh

(Full credit to @daniel-j-g)

Brett Rigby
  • 6,101
  • 10
  • 46
  • 76