Fahad Amin
Fahad Amin

Reputation: 93

Dynamically set value for asp-route-id using javascript without foreach loop

I am working on an ASP.Net MVC 6 application. The default index view usually has links for Edit, Details and Delete inside the foreach loop like

@foreach (var item in Model) {
        <tr>
            <td>@Html.DisplayFor(modelItem => item.FirstName)</td>
            <td>@Html.DisplayFor(modelItem => item.LastName)</td>
            <td>
                <a asp-action="Edit" asp-route-id="@item.SpeakerId">Edit</a> |
                <a asp-action="Details" asp-route-id="@item.SpeakerId">Details</a> |
                <a asp-action="Delete" asp-route-id="@item.SpeakerId">Delete</a>
            </td>
        </tr>
    }

My requirement is such that the links for View, Edit & Delete should appear outside the table and the row should be selected using radio buttons column.

Is there any way to set the asp-route-id attribute dynamically using the onchange event of radiobutton?

I have tried something link this

function radioSelected() {        
        var routeId = $('input[name="selectRecord"]:checked').val();
        var links = "<a asp-action='Details' asp-route-id=" + routeId + ">View Details</a> | "
                    + "<a asp-action='Edit' asp-route-id=" + routeId + ">Edit</a> | "
                    + "<a asp-action='Delete' asp-route-id=" + routeId + ">Delete</a>";

        document.getElementById("actions").innerHTML = links;
    }

but the asp-route-id and asp-action attributes don't work this way.

Upvotes: 4

Views: 4861

Answers (1)

adem caglin
adem caglin

Reputation: 24083

If possible, you can use jquery. I added below part to handle your case:

<a id="lnkEdit" data-url-prefix="@Url.Action("Edit")">Edit</a> |
<table id="tableSelect">
    @foreach (var item in Model)
    {
        <tr data-item-id="@item.SpeakerId">
            <td><input name="selectRow" type="radio"></td>
            <td>@Html.DisplayFor(modelItem => item.FirstName)</td>
            <td>@Html.DisplayFor(modelItem => item.LastName)</td>
        </tr>
    }
</table>


<script type="text/javascript">
     $(function () {
         $('#tableSelect tr').click(function () {
             $(this).find('td input:radio').prop('checked', true);
             $("#lnkEdit").attr("href", $("#lnkEdit").data("url-prefix") + "/" + $(this).data("item-id"));
         })
     });
</script>

Upvotes: 0

Related Questions