Proper way to call a method on button click

Mitchelln11

Active member
Joined
Apr 10, 2020
Messages
39
Programming Experience
Beginner
I want to fetch a REST API endpoint, but I want to do it on button click.
Is there a proper way to do this?

I'm using the following:
```
<input type="button" value="Fetch Parks" onclick="location.href='@Url.Action("FetchParkApi", "Park")'" />
```
which is a button that's meant to run a method called "FetchParkApi" that's located on the ParkController.

I have also used :
```
@Html.ActionLink("Fetch Parks", "FetchParkApi", "Park")
```
These methods work, it's only that the method, when finished, wants to go to a page called FetchParkApi which is on the ParkController. I just want it to go back to the Index view of the Park
 
As per the design of HTML, action links are supposed to navigate to another URL.

If you don't want to navigate to the new URL, but rather invoke a REST API, then make your button click handler invoke an AJAX request, and then when the request returns, then navigate to the index page.
 
As per the design of HTML, action links are supposed to navigate to another URL.

If you don't want to navigate to the new URL, but rather invoke a REST API, then make your button click handler invoke an AJAX request, and then when the request returns, then navigate to the index page.
So no HttpClient at all then? AJAX would be a better approach?
I was using HttpClient inside my FetchParkApi method
 
Recall that <input> is going to be running in the web browser of the user who is visiting your website. Unless you are already using Blazor, then it's going to really hard to get some C# code running on the client side browser.
 
Recall that <input> is going to be running in the web browser of the user who is visiting your website. Unless you are already using Blazor, then it's going to really hard to get some C# code running on the client side browser.
I think I'm lost then.
So I wouldn't be using <input>?
What about <button>?

If neither, how would I invoke my call to the REST endpoint?

From your first comment, it sounds like I don't want an action link. I in fact do not want to go to a new URL.
 
It's the same deal with the HTML <button> element. It is still running client side in the browser.

It maybe worth your while to review how regular HTML web pages work. Avoid reading ASP.NET WebForms documents which try to blur the lines between real HTML vs. WebForms controls.

As much as I despite W3Schools, this sample they have about how to invoke AJAX on a button click is actually simple and direct to the point:


Instead of the "demo_text.txt", use your REST API URL. And then change the success handler to navigate to your index page.
 
Back
Top Bottom