ITWorker ITWorker - 4 months ago 24
Javascript Question

ASP.NET MVC Razor repeated button in table is non-responsive past the first button

In a cshtml file, I have defined a table from a model as follows:

foreach (AppUser user in Model)
{
if (!(user.UserName.ToLower().Equals("admin")))
{
<tr>

<td>@user.UserName</td>
<td>@user.Email</td>
<td>
<button class="btn btn-primary btn-xs"
id="edituserbutton" data-id="@user.Id" name="@user.Id">
Edit
</button>
</td>

<td>
@using (Html.BeginForm("Delete", "Admin",
new { id = user.Id }, FormMethod.Post, new { @id = "manageusersform", name = user.UserName }))
{

<button class="btn btn-danger btn-xs"
type="submit">
Delete
</button>
}
</td>
</tr>
}
}


The Delete button works fine for all the rows, however, the Edit button only works on the first row. Here are the respective functions in jQuery within the document ready function:

Edit


$("#edituserbutton").click(function (event)
{

event.preventDefault();
// alert("edit clicked");

$.ajax({
url: "/Admin/Edit",
cache: false,
data: {id : $(this).data('id')}
}).done(function (htmlResponse) {
$("#tabs-1ua").html(htmlResponse);
});


});


I used the alert for testing, and past the first row, it was never fired, despite having the id
edituserbutton
on the Edit button in each row.

Delete


$("form#manageusersform").submit(function (event)
{

event.preventDefault();
var form = $(this);
var userNameSelected = form.attr('name');



confirm("Are you sure you want to delete user \"" + userNameSelected + "\"?").then(function (yesno) {

if (yesno === "yes") {


$.post(form.attr("action"), form.serialize(), function (res) {



if (res.status === "success") {

console.log(res);

$.ajax({
url: "/Admin/Index",
cache: false,
data: {}
}).done(function (htmlResponse) {
$("#tabs-1ua").html(htmlResponse);
});
//end of updating management tab

}
else {

console.log(res);

}
});


}


});


});


In the Delete function above, I am using a custom confirmation dialog, that is what the yesno is for.

What should I do to fix the issue with the Edit buttons?

Thank you.

Answer

Your markup is wrong. You are having same id for all the buttons. That is invalid. your Id's should be unique.

I suggest you remove the id from the markup and use a css class for your jQuery selector.

<button class="btn btn-primary btn-xs delBtn" data-id="@user.Id"> Edit </button>

and

$(function(){

   $("button.delBtn").click(function(e){
       e.preventDefault();
       var btnClicked = $(this);
       var idToSend =  btnClicked.data("id");

       //do your ajax call.

    });

});