0

I have the following code in my .cshtml file

<form asp-page-handler="button"  method="post">
    <label class="form-label">Username</label>
    <input  name="username" id="username" placeholder="Username" type="text" />
    <button class=button-gap onclick="@grabStats()">Find stats</button>   
</form>

The problem is the function grabStats() runs on pageLoad and returns an error

Is there a reason why an onclick event is fired when the page loads without the button being clicked?

For more clarity:

@functions{
    private async Task<string> Stats()
    {

        var username  = Request.Form["username"];
        var client = new HttpClient();
        client.DefaultRequestHeaders.Add("User-Agent", "Activity chooser");
         String url = "https://secure.runescape.com/m=hiscore_oldschool/index_lite.ws?player=" + username;
          HttpResponseMessage response = await client.GetAsync(url);
          response.EnsureSuccessStatusCode();
          string responseBody = await response.Content.ReadAsStringAsync();
        return responseBody;
    }




    private String grabStats()
    {

        var statsRaw = Stats().Result;

        Models.Player player = new Models.Player();
        return ""; //Later return useful stuff
    }
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
D74
  • 41
  • 5
  • Is this `grabStats` function in the client-side JavaScript code, or the server-side C# code? What's the error? – David Aug 03 '22 at 19:21
  • 1
    Hi, sorry I should have specified more, its in the server-side C# code The error is due to performing .Result on a Task I think without it having a value (hence why I'm trying to stop the onclick firing before page load, not sure if that's the correct way of doing it or not. I've edited my main post – D74 Aug 04 '22 at 01:13
  • @D74: The duplicate uses PHP for its examples but the concept is identical and language agnostic. The server-side code runs on the server before the page is even sent to the client. What you’re doing is executing that function server-side and setting whatever it returns as the client-side click handler. Whatever the goal is, the implementation needs to be re-thought. – David Aug 04 '22 at 01:21
  • As an aside, calling .Result on a Task is almost always the wrong approach, unless you really know what’s going on under the hood. Taking a step back… If this operation should be performed when a button is clicked, you’re probably looking to use AJAX (if it needs to be server-side at all). If the operation is async, make it async all the way up to the endpoint being invoked by the AJAX request. – David Aug 04 '22 at 01:26
  • Awesome thankyou, i'll take a read through and get a better understanding on both issues – D74 Aug 04 '22 at 11:06

0 Answers0