Asp.net核心删除按钮不能正常工作

时间:2017-08-16 21:50:49

标签: javascript jquery asp.net

我有这样的观点:

<div class="GridContainer">
<div>
    <div class="row gridHeader">
        <div class="small-9 columns">Member Name</div>
        <div class="small-2 columns">Date Registered</div>
    </div>
    @foreach (var member in Model.Members)
    {
        <div class="row">
            <div class="small-9 columns">@member.MemberName</a></div>
            <div class="small-2 columns">@member.DateRegistered</div>
            <input type="hidden" asp-for="@member.Id" />
            <a id="btnMemberDelete" href="#">Delete</a>
        </div>
    }
</div>

我的javascript:

<script type="text/javascript">
    $(document).ready(function () {
        $('#btnMemberDelete').click(function () {
            var id = $(this).closest("div").find("input:hidden[name='member.Id']").val();
            var url = '@Url.Action("DeleteMembers", "Member")' + "?id=" + id;
            openMemberDialog(url);
        });
    });
</script>

删除按钮仅适用于此刻的第一行。如果说我有4行,则其他3的删除按钮甚至不会注册。它甚至不会打开对话框。我在这里找不到一些东西,因为代码似乎对我来说是正确的。

谢谢!

2 个答案:

答案 0 :(得分:0)

您需要为每个删除按钮指定一个唯一ID。或者你可以给你的锚标签一个classname而不是id。

<div class="GridContainer">
<div>
    <div class="row gridHeader">
        <div class="small-9 columns">Member Name</div>
        <div class="small-2 columns">Date Registered</div>
    </div>
    @foreach (var member in Model.Members)
    {
        <div class="row">
            <div class="small-9 columns">@member.MemberName</a></div>
            <div class="small-2 columns">@member.DateRegistered</div>
            <input type="hidden" asp-for="@member.Id" />
            <a class="btnMemberDelete" href="#">Delete</a>
        </div>
    }
</div>


<script type="text/javascript">
$(document).ready(function () {
    $('.btnMemberDelete').click(function () {
        var id = $(this).closest("div").find("input:hidden[name='member.Id']").val();
        var url = '@Url.Action("DeleteMembers", "Member")' + "?id=" + id;
        openMemberDialog(url);
    });
});
</script>

答案 1 :(得分:0)

小提琴here

如上所述,您需要拥有一个ID或使用一个类。在上面的解决方案中,我使用了类似的类:

  $(document).ready(function () {
        $('.btnMemberDelete').click(function (e) {
        e.preventDefault();
            var id = $(this).closest("div").find("input:hidden[name='member.Id']").val();

           console.log(id)
        });
    });

同样更正您的HTML:

@foreach (var member in Model.Members)
{
    <div class="row">
        <div class="small-9 columns">@member.MemberName</a></div> // remove the '</a>' here
        <div class="small-2 columns">@member.DateRegistered</div>
        <input type="hidden" asp-for="@member.Id" />
        <a class="btnMemberDelete" href="#">Delete</a>
    </div>
}