Search code examples
asp.net-coreonclickasp.net-core-mvc.net-6.0

.NET Core 6 - How to pass data on click


I have a foreach loop that iterates through a Model and displays the data in a table. I want to pass the id (or any data from the model) to an element outside the foreach loop whenever I click on a button that corresponds to an entry in the loop, how can I do so?

Example:

<tbody>
    @foreach (var incident in Model)
    {
        <tr>
            <th>@incident.Title</th>
            <td>@incident.CustomerId</td>
            <td>@incident.ProductId</td>
            <td>@incident.DateOpened</td>
            @{
                var id = @incident.IncidentId;
            }
            <td><a asp-controller="Incident" asp-action="Edit" asp-route-id="@incident.IncidentId" ><i class="fa-solid fa-pen-to-square"></i></a></td>
            <td >
                <i class="fa-solid fa-trash-can hover:cursor-pointer" > <<-- When clicked, store the model id, modelId = @incident.IncidentId
                </i>
           </td>
       </tr>
    }         
</tbody>

//Now I should have access to the exact variable (id) and pass it to other elements 

Solution

  • You can achieve it with Javascript.

    Concept

    1. Label the delete button with the class delete.
    2. Use data-* attribute to store the id value.
    3. Create click event listener for all elements with (class) .delete.
    <tbody>
        @foreach (var incident in Model)
        {
            <tr>
                <th>@incident.Title</th>
                <td>@incident.CustomerId</td>
                <td>@incident.ProductId</td>
                <td>@incident.DateOpened</td>
                @{
                    var id = @incident.IncidentId;
                }
                <td><a asp-controller="Incident" asp-action="Edit" asp-route-id="@incident.IncidentId" ><i class="fa-solid fa-pen-to-square"></i></a></td>
                <td>
                    <i class="delete fa-solid fa-trash-can hover:cursor-pointer" data-id="@incident.IncidentId">
                    </i>
               </td>
           </tr>
        }         
    </tbody>
    
    <div>
      <label>Selected Id:</label>
      <span id="selectedId"></span>
    </div>
    
    <script type="text/javascript">
        (function () {
            var deleteBtns = document.querySelectorAll('.delete');
            deleteBtns.forEach(btn => {
                btn.addEventListener('click', getSelectedId);
            });
        })();
    
        function getSelectedId() {
            var id = this.getAttribute("data-id");
    
            document.getElementById("selectedId").innerHTML = id;
        }
    
        window.onbeforeunload = function () {
            var deleteBtns = document.querySelectorAll('.delete');
            deleteBtns.forEach(btn => {
                btn.removeEventListener('click', getSelectedId);
            });
        }
    </script>
    

    Sample .JS Fiddle