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 ></i></a></td>
<td >
<i > <<-- 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
CodePudding user response:
You can achieve it with Javascript.
Concept
- Label the delete button with the class
delete
. - Use
data-*
attribute to store the id value. - 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 ></i></a></td>
<td>
<i 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>