5
votes

This weekend a lot of struggle with a View Component.

I try to add a dropdownlist that does an auto postback onchange. This dropdownlist is on a view component.

I have 2 problems:

  1. I don't get the asp-page-handler after the post, does it work like I implemented it on the form-tag?
  2. Post calls method public void OnPost on razor page containing view component. I would think it would be better to have a method on the View Component like OnChangeProject?

The code of my View (View Component):

<form asp-page-handler="ChangeProject" method="post">

    @Html.AntiForgeryToken()
    @Html.DropDownList("id", new SelectList(Model, "Id", "Id"), new { onchange = "this.form.submit()" })

</form>

Thanks in advance!!

2

2 Answers

2
votes

I exprienced the same problem and the way i fixed it is already answered in your question.

The form call is made at the page where you got your View Component embedded. I don't think it would be even possible to call a handler in your View Component with asp-page-handler as this is Razor Pages tag helper.

The way i got it work is simply putting the page-handler method on the PageModel that is embedding the View Component. In your case you can simply implement this handler on your Razor Page:

public IActionResult OnPostChangeProject()
{
    // ... do Something
}

I don't know though how it would work to trigger a controller method in your View Component. Possibly create a new Controller class and route to it with asp-controller and asp-action in your form tag.

0
votes

It's possible to create a combo (Controller/ViewComponent) by decorating the controller with a ViewComponent(Name="myviewcomponent").

Then create the invokeasync as usual, but because the controller doesn't inherit from a ViewComponent, the return result would be one of the ViewComponent result (ViewViewComponentResult, et).

The form in the viewcomponent can then have a button with asp-controller/action tag helpers targetting the controller/action.