I want the exact target on which the click event has been triggered in ASP.NET Core blazor. Is this achievable?
Adding a button onclick event The first thing we need to is to create a NewComment property. This will store the textarea value. We then need to bind our NewComment property to the textarea value. We do that by using the @bind attribute.
You can use @ref to get a reference to a DOM object, then pass it as a parameter to your handler function.
You can then pass it as a parameter to the JS Interop.
For example:
Counter.razor
@page "/counter"
@using Microsoft.JSInterop
@inject IJSRuntime JSRuntime
<h1>Counter</h1>
<p>Current count: @currentCount</p>
<p>Last button clicked: @lastButtonClicked</p>
<button @ref=button1 class="btn btn-primary" @onclick="@(()=>IncrementCount(@button1))">Click me</button>
<button @ref=button2 class="btn btn-primary" @onclick="@(()=>IncrementCount(@button2))">Click me</button>
@code {
private ElementReference button1;
private ElementReference button2;
private int currentCount = 0;
private string lastButtonClicked = "None";
private async void IncrementCount(ElementReference element)
{
currentCount++;
await JSRuntime.InvokeVoidAsync("setElementText", element, "I was clicked");
}
}
And make sure to add this script to Index.html
<script>
window.setElementText = (element, text) => { console.log(element); element.innerText = text; }
</script>
Reference: https://docs.microsoft.com/en-us/aspnet/core/blazor/javascript-interop?view=aspnetcore-3.1#detect-when-a-blazor-app-is-prerendering
In .razor file:
@for (int i = 0; i < 1000; i++)
{
int j = i;
<input type="text" @onchange='eventargs => HandleValueChange(eventargs, "my first textbox from row " + j.ToString())' />
<input type="text" @onchange='eventargs => HandleValueChange(eventargs, "my second textbox from row " + j.ToString())' />
}
@code {
protected void HandleValueChange(ChangeEventArgs evt, string elementID)
{
}
}
Note: The key here is the int j = i declaration in the inner-loop scope ... if you pass i to the event handler you will always get '1000' i.e. it's final value from the outer loop scope
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With