Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Blazor @onlick how to get HTML element clicked on

I am currently learning C# Blazor framework and I am faced with question, how to get HTML element I clicked on?

I need it to get it's position in DOM and in parent HTML element.

For example, classic way with JQuery:

$('selector').click(function (event) {
    alert($(this).index());
});

http://jsfiddle.net/bCTAh/

I know, that there is @onclick attribute in Blazor, for example:

<tr @onclick="OnYes">...</tr>

@functions {
    ElementReference inputTypeFileElement;

    public async Task MainTableOnClick(MouseEventArgs e)
    {
        Console.WriteLine("clicked!");
    }
}

How can I get index of TR HTML element that was clicked on?

My task is convert Windows Form app to Web-version. The old Windows Form has DataGridView, each row of that has onClick event and Tag Object too. When some of row of the DataGridView clicked, onClick get's Tag Object of the row and used it to fill data to another DataGridView's on the form. So, I need to know, what row clicked to get data from some object (it can be DataTable, or, to be more simply, Array). Based on index of row and index in Array, I need to get data for filling another tables on Web Page.

So, first table is Clients (name, surname, etc...).

When some of row with Client has been clicked, I need to get row (Client) index in the table. By that index I'll get data from Array of Clients. By found Client object I plan to fill another tables on the page dynamically.

like image 645
Arthur Avatar asked Dec 14 '22 10:12

Arthur


2 Answers

In this case, you can use JSInterop

Or

<tr @onclick="() => TrClickedAtIndex(0)">...</tr>

@code {
    ElementReference inputTypeFileElement;

    public void TrClickedAtIndex(int index)
    {
        Console.WriteLine($"tr clicked at index {index}!");
    }
}

like image 151
agua from mars Avatar answered Dec 17 '22 22:12

agua from mars


If you want to get the element you can use a @ref to return an element, but generally in Blazor you're not interest in the elements (as you might in JQuery) but what they relate to.

I created this simple BlazorFiddle that lists three strings in a table. It's similar to the other answer but it demonstrates a little wrinkle - when passing a value from a loop or enumeration you need to assign it.

https://blazorfiddle.com/s/br8lwsl2

This shows a table for three strings. When you click a row, it passes the data item from the clicked row - not just an index.

    int index = i;
    <tr @onclick="()=> ClickedRow(list[index])" ><td>

Hope this helps

like image 28
Quango Avatar answered Dec 17 '22 23:12

Quango