Search code examples
ajaxasp.net-coremodel-view-controllerasp.net-mvc-5modal-dialog

Passing Model.ID to modal and running a method


I have a table, and I want to pass a row (dataID) to a method in my controller.

$(document).ready(function () {
    $('.modalRed').click(function () {
            var url = $('#ledgerModal').data('url');
            $.get(url, function (data) {
                $("#ledgerModal").html(data);
                $("#ledgerModal").modal('show');
            });
    });

});
<table class="tableCustomTableOne" width="40%">
    <tr>
        <th nowrap="nowrap">
            @Html.LabelFor(model => model.Name, htmlAttributes: new {@class = "control-label col-md-2" })
        </th>
        <th nowrap="nowrap">
            @Html.LabelFor(model => model.Data, htmlAttributes: new { @class = "control-label col-md-2" })s
        </th>
    </tr>
    @foreach (var item in (ViewBag.MainLedger as List<ModalApp.Models.Ledger>))
        {
            <tr class="modalRed">
                <td nowrap="nowrap">
                    @Html.DisplayFor(modelItem => item.Name)
                </td>
                <td nowrap="nowrap">
                    @Html.DisplayFor(modelItem => item.Data),
                </td>
            </tr>
            <tr class="modal fade" id="ledgerModal" role="dialog" data-url='@Url.Action("detLedgerPartial","Ledger", new { id = item.Id })'></tr>
        }
</table>

But it only opens information about a row with first "id" How can I make it so it sends ID from specific row?


Solution

  • Id selector always select the first element with the specify id, since you have many <tr> with the same id ledgerModal, so only the first one will be selected. Change your jquery like this:

    $('.modalRed').click(function () {
        var $tr = $(this).next('tr');
        var url = $tr.data('url');
        console.log(url);
        $.get(url, function (data) {
            $tr.html(data);
            $tr.modal('show');
        });
    });