Home > Back-end >  asp-route always uses the first Id of html for each loop because of javascript dialog
asp-route always uses the first Id of html for each loop because of javascript dialog

Time:01-28

I am displaying data from my c# backend with a for each loop in the html page. When deleting an element, I am opening a modal dialog to confirm. But because this involves javascript, the delete function after the confirmation always is the one for the first item of my data. So it seems that the calling of javascript restarts the for each loop.I always get the first id in the backend.

The relevant html code:

<form method="post">
    <table >
        <thead>
        <tr>
            <th>Id</th>
            <th>Name</th>
        </tr>
        </thead>
        <tbody>
        @foreach (var experiment in Model.MainExperimentsTests)
        {
            <tr>
                <td>@experiment.Id</td>
                <td>@experiment.ExperimentTestName</td>
                <td>
                    <a 
                       onclick="showDeleteDialog()">
                        <i ></i>
                    </a>
                    <dialog id="deleteDialog">
                        Do you really want to delete?
                        <button asp-page-handler="Delete" asp-route-experimentId="@experiment.Id"
                        value="confirm">Ok</button>
                        <button onclick="closeDeleteDialog()" type="reset">Cancel</button>
                    </dialog> </td>

            </tr>
        }

        </tbody>
    </table>
</form>

Javascript code:

<script>
    function showDeleteDialog() {
        document.getElementById("deleteDialog").showModal();
    }
    function closeDeleteDialog() {
        document.getElementById("deleteDialog").close();
    }
</script>

I tried saving the id in javascript and doing an ajax post call from there instead of using the "asp-page-handler" and "asp-route-experimentId", but I couldn't get it to work properly. I tried different ways to open a dialog, but I don't want the default pop up from the browser, I want my own modal dialog.

Does anyone know how I can get the right id to be passed to asp-route? Is my structure completely wrong? I appreciate your help.

CodePudding user response:

You need unique dialog ids. For example you can concat experiment id to the dialog id. Try something like the following:

<a  onclick="showDeleteDialog(@experiment.Id)">
    <i ></i>
</a>
<dialog id="[email protected]">
   ...
    <button onclick="closeDeleteDialog(@experiment.Id)" type="reset">Cancel</button>
</dialog> 

<script>
    function showDeleteDialog(experimentId) {
        document.getElementById("deleteDialog_"   experimentId).showModal();
    }
    function closeDeleteDialog(experimentId) {
        document.getElementById("deleteDialog_"   experimentId).close();
    }
</script>
  • Related