Edit Method in ASP.Net Core MVC why 'data-id' in javascript always contains 1 i want if i select item 2 so data-id is 2

(THIS IS JS)
$("#editBtn").click(function () {
    $.ajax({
        url: '/Products/Edit',
        data: {
            ID: $(this).attr('data-id')
        }
    })
        .done(function (response) {
            $("#actionContainer").html(response);
        })
        .fail(function (XMLHttpRequest, textStatus, errorThrown) {
            alert("Fail");
        });
});

(THIS HTML CODE)
<button type="button" id="editBtn" data-id="@item.ID">New</button>

‘this is edit method in asp.net core mvc using ajax
i want ‘data-id’ according to selected item, if i select item 2 so data-id is 2′

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

i want ‘data-id’ according to selected item, if i select item 2 so data-id is 2′

If your button(s) are rendered in table row(s), please change id attribute to class attribute (id should be unique), like below.

@foreach (var item in Model)
{
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.ID)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Name)
        </td>
        @*code of other fields*@
        <td>
            <button type="button" class="editBtn" data-id="@item.ID">New</button>
        </td>
    </tr>
}

Modify your code using the .class selector $(".editBtn")

$(".editBtn").click(function () {
    $.ajax({
        url: '/Products/Edit',
        data: {
            ID: $(this).attr('data-id')
        }
    })
        .done(function (response) {
            $("#actionContainer").html(response);
        })
        .fail(function (XMLHttpRequest, textStatus, errorThrown) {
            alert("Fail");
        });
});

Besides, if the button is a separate element in your view page, you may need to dynamically change data-id based on selected item in select change event etc.

$("#editBtn").attr("data-id", 2)

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply