Search code examples
c#asp.net-coreasp.net-core-viewcomponent

View components can't link to POST action methods?


I have a view component which contains some action links that points to different action methods in the home controller, like this:

<a asp-action="Update" asp-route-id="@item.ProductId">Update quantity</a>
<a asp-action="Details" asp-route-id="@item.ProductId">@item.ProductTitle</a>

The action method Details, which is a GET-method, is being executed as expected.

But when I click on the Update-link, I'm directed to a blank page with the url of /Home/Update/5, for instance, and nothing more happens. This is also the case even if I run in debug mode and set a breakpoint on the first line of the Update-method. Update is a POST-method. Does this matter?

In either case, Update is not executed.

What is going on?


Solution

  • You can't call POST request by clicking a link.

    You either need to use ajax or form for this. It depends on your needs.

    Use form:

    <form asp-action="Update" asp-route-id="@item.ProductId" method="post">
        <button type="submit">Update quantity</button>
    </form>
    

    Use ajax: (assume you have jQuery)

    $('<update-link-selector>').on('click', function (e) {
        e.preventDefault();
        var href = $(this).attr('href');
    
        $.post(href).done(function(response, status, xhr) {
            //success 
        }).fail(function(err) {
            //error
        });
    });