简体   繁体   中英

Why onclick event triggered when page is reloaded

So, I have a button in my .cshtml file:

<div>
    <button id='btn-next' name='next' type='button' onclick='function f() {
         @{ 
            Console.WriteLine("BeforeCalling");
            myClass test = new myClass();
            test.TestMethod("123");
            Console.WriteLine("AfterCalling");
          }
          }' class='btn btn-block btn-secondary'>justAButton</button>
</div>

Why does it 'clicked' (I see the console output in terminal) when my page reloads? But, if I click the button manually - nothing happens. It works only on page reload.

onclick is a client-side JavaScript event handler. So whatever you want to do there happens in the user's browser.

However, Razor syntax is executed by the server before anything is sent to the client. Razor is what is being executed in order to generate the HTML that the server sends to the user which then gets interpreted by the browser. But at the time the browser renders the HTML (and registers any JavaScript event handlers), the server is already done.

So what this basically means is that you cannot have server-side code run as part of client-side events. The Razor code you have there runs when the HTML gets generated and none of that logic is sent to the client (you can check that by looking at the HTML source in your browser).

If you want the server to do something when a client-side event occurs, you will need to have the client (=the browser) communicate back to the server, eg using AJAX requests. Alternatively, you could look into Blazor if you want to approach this without having to deal with JavaScript.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM