I am using Blazor in a project. I am assigning data-id to each table row in foreach loop. Then I want to find/get each element by data-id when some one click on this table row. My question is that how can I use c# in blazor for this jquery statemetn like $("#tableRow1").attr("data-id").
Or just mentioned plz the best way to access DOM element by id, class, attribute. thanks
Using the JS Interop functionality should allow you to get the values of a particular element by ID.
Here is the MS documentation regarding this feature.
The flow would be something like:
Setting up the component reference object:
private DotNetObjectReference<YOUR_COMPONENT_NAME> objRef;
protected override void OnInitialized()
{
//objRef gives our JS Interop functions the ability to call c# methods (and do other things)
//that are specific to this component instance.
objRef = DotNetObjectReference.Create(this);
}
We then pass this object when calling the initial JS Interop function:
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
await JS.InvokeAsync<string>("InteropFunctions.getAllRowsAndSetListener", objRef);
}
}
JS Interop function example:
window.InteropFunctions = {
getAllRowsAndSetListener: (componentObjRef) => {
let rows = document.querySelectorAll("tableRow");
if (rows.length) {
rows.forEach(row => row.addEventListener("click", (e) => {
await componentObjRef.invokeMethodAsync("DoSomethingWithId", e.target.id);
}))
}
}}
C# method in component that will take the ID and do something:
[JSInvokable]
public void DoSomethingWithId(string id)
{
// ... do something with ID
}
It should be noted that you can pass anything back to the C# method as long as its JSON serializable. So you could pass back typed objects, arrays, etc.