Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoke ViewComponent using javascript

I have a web page with a couple of view components, when I click on these components I open a simple editor for it, see image below. If I edit the text and hit enter, I would like to rerender the view component and not the hole page. Is it possible to invoke a view component using javascript to get this behaviour?

enter image description here

like image 865
marcus Avatar asked Sep 28 '22 17:09

marcus


2 Answers

With updates, you should now be able to do this with asp.net core. You can return a ViewComponent from an IActionResult, then just call it with jQuery:

[Route("text-editor")]
public IActionResult TextEditor()
{
    return ViewComponent("TextEditorViewComponent");
}

Then this can be called from your View with something as simple as this:

function showTextEditor() {
    // Find the div to put it in
    var container = $("#text-editor-container");
    $.get("text-editor", function (data) { container.html(data); });
 }

If you need to pass parameters to the ViewComponent you can do so in the IActionResult (maybe they trickle through from the View to there, to the view component, etc).

like image 157
b.pell Avatar answered Oct 03 '22 01:10

b.pell


This is not possible today but you could build a standard proxy for viewcomponents if you'd like though (similarly you could build a proxy to partial views). e.g. you a catchall attribute route on an action.

like image 30
marcus Avatar answered Oct 03 '22 00:10

marcus