Search code examples
c#asp.netasp.net-mvc-4blazorblazor-webassembly

How to find value by data attribute in ASP Blazor like in jquery ($("#divID").attr("data-id"))?


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


Solution

  • 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:

    1. Setup a JS interop function that takes a component reference object. This function will grab all table rows by class name.
    2. Set an 'on-click' event that will grab the ID of the row that was clicked.
    3. Have the event handler send the ID back to the c# component by calling a c# function passed via the component reference object.

    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.