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′

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 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)


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

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x