Binding data to an @onclick event

Nigel 291 Reputation points
2023-12-22T10:15:01.1366667+00:00

Hi, I am trying to transfer what was a WPF desktop app to a Blazor app (.net 8). I tried the following code in Telerik REPL for Blazor and it worked as expected:

<h3>AntCalc</h3>  
<label>Please enter frequency in Mhz: </label> 
<input @bind="freq" /> 
<p role="status">Wavelength: @wavelength m.</p>  

<button class="btn btn-primary" @onclick="Calc">Enter</button>

@code {     

public double freq { get; set; }     
public double wavelength = 0;      
private void Calc()     
	{         
		wavelength = 300 / freq;     
	}       
}


However, when I transfer it to the app in development in VS, with the addition of an @page directive at the top, the onclick event doesn't bind to the Calc() function as it should and the result remains '0'. Probably something simple that I am overlooking but it's been bugging me for days now. GitHub repo is at https://github.com/m0cvo/AntCalcB Any help would be appreciated.

Developer technologies .NET Blazor
Developer technologies C#
0 comments No comments
{count} votes

Accepted answer
  1. AgaveJoe 30,126 Reputation points
    2023-12-22T12:42:21.6066667+00:00

    Add @rendermode InteractiveWebAssembly to the top of the page. Next, build and restart the application.

    @page "/frequency"
    @rendermode InteractiveWebAssembly
    <h3>Frequency</h3>
    
    <label>Please enter frequency in Mhz: </label>
    <input @bind="freq" />
    <p role="status">Wavelength: @wavelength m.</p>
    
    <button class="btn btn-primary" @onclick="Calc">Enter</button>
    
    
    @code {
    
    	public double freq { get; set; } = 1;
    	public double wavelength = 0;
    	private void Calc()
    	{
    		wavelength = 300 / freq;
    	}
    }
    
    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.