简体   繁体   中英

Asp.Net Core 5.0 Using jQuery in Partial View

I am using a partial view with Ajax to display User Data on the Main View. The script runs from the main view.

Now I want to add a 'delete' button to the results in the partial, but I am having problem in writing a script with an ajax call in the partial view.

How can I solve this problem by treating the partial form data with jQuery and Ajax?

This is my partial view:

@foreach (var i in Model.Users)
{

        <div>
            <form id="deletForm">
                <input name="Id" id="Id" value="@i.Id" hidden />
                <input name="UserId" id="userId" value="@i.ApplicationUserId" hidden />
                <button type="submit" class="close-icon" id="deleteBtn"></button>
            </form>
            <div class="class" data-toggle="tooltip" title="@i.ApplicationUser.FullName">@i.ApplicationUser.Name.ToUpper()</div>
        </div>
    
}



<script>
    $("#deleteBtn").click(function (e) {
        e.preventDefault();
        var formdata = $("#deletForm").serialize();
        alert(formdata);
        alert('I got here');

    });
</script>

Now I want to add a 'delete' button to the results in the partial, but I am having problem in writing a script with an ajax call in the partial view.

Please note that you put the <form id="deletForm"> within @foreach looping in your partial view, which would cause many html elements with same id attribute.

To achieve your requirement, you can try to modify the code like below.

In partial view

@foreach (var i in Model.Users)
{

    <div>
        <form class="deletForm">
            <input name="Id" value="@i.Id" hidden />
            <input name="UserId" value="@i.ApplicationUserId" hidden />
            <button type="submit" class="close-icon deleteBtn"></button>
        </form>
        <div class="class" data-toggle="tooltip" title="@i.ApplicationUser.FullName">@i.ApplicationUser.Name.ToUpper()</div>

}

In main view

<script>
    $(function () {
        $(".deleteBtn").click(function (e) {
            e.preventDefault();
            var formdata = $(this).parent(".deletForm").serialize();
            alert(formdata);
            alert('I got here');

            //code logic here of making ajax request(s)
        })
    })
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM