簡體   English   中英

@foreach 循環中的多種形式。 如何使用 javascript 異步提交一個。 C# 核心剃刀

[英]Multiple forms in @foreach loop. How do I submit one asynchronously with javascript. C# core Razor

帶有許多項目的購物車如何使用 JavaScript 異步刪除任何項目這是我迄今為止的工作。 任何人都可以改進嗎?

您的幫助將不勝感激。 祝你有美好的一天

好的,如果您從列表頂部刪除項目,則此方法有效,但如果您從其他位置刪除項目,則失敗。

問題似乎是表單名稱都是相同的“刪除”而沒有任何索引。

問題是我不確定如何進行。

document.forms['remove'].onsubmit = () => {
        let formData = new FormData(document.forms['remove']);
        fetch('/sales/cart?handler=RemoveItem', {
            method: 'post',
            body: new URLSearchParams(formData)

    })
        .then(() => {
                var url = "/sales/cart?handler=CartPartial";
                console.log(url)
                $.ajax({
                    url: url,
                    success: function (data) {
                        $("#exampleModal .modal-dialog").html(data);
                        $("#exampleModal").modal("show");
                        //alert('Posted using Fetch');
                    }
                });
            });
        return false;
    }

   
    <pre>
       @foreach (var item in Model.Items)
       {
          <form name="remove" method="post">
            <h4 class="text-left text-body">@item.Price.ToString("c")
            <button class="btn btn-sm" title="Trash"><i style="font-size:large" 
             class="text-warning icon-Trash"></i></button>
            </h4>
            <input type="hidden" asp-for="@Model.Id" name="cartId" />
            <input type="hidden" asp-for="@item.Id" name="cartItemId" />
          </form>

       }
   </pre>

Update


----------
New markup
I added an index to the id and included an onclick event.


    <form method="post" id="@i" onclick="removeItem(this.id)">
    <button class="btn btn-sm" title="Trash">Item One</button>
    <input type="hidden" asp-for="@Model.Id" name="cartId" />
    <input type="hidden" asp-for="@item.Id" name="cartItemId" />
    </form>


and create a new function that captured the form id including it in a constant.

    <script>
    function removeItem(formId) {
        const form = document.getElementById(formId);
        form.onsubmit = () => {
            let formData = new FormData(form);
            fetch('/sales/cart?handler=RemoveItem', {
                method: 'post',
                body: new URLSearchParams(formData)
            })
                .then(() => {
                    var url = "/sales/cart?handler=CartPartial";
                    console.log(url)
                    $.ajax({
                        url: url,
                        success: function (data) {
                            $("#exampleModal .modal-dialog").html(data);
                            $("#exampleModal").modal("show");
                            //alert('Posted using Fetch');
                        }
                    });
                });
            return false;
        }
    }
    </script>




If anybody can improve on this please post it here.
Thanks.


Updates code behind Cart.cshtml.cs

    using System;
    using System.Threading.Tasks;
    using Malawby.Models;
    using Malawby.Services.Interfaces;
    using Microsoft.AspNetCore.Http;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Mvc.RazorPages;

    namespace Malawby.Pages.Sales
    {
    public class CartModel : PageModel
    {
        private readonly ICartRepository _cartRepository;
        public CartModel(ICartRepository cartRepository)
        {
            _cartRepository = cartRepository ?? throw new 
        ArgumentNullException(nameof(cartRepository));
        }

        [BindProperty]
        public Cart Cart { get; set; } = new Cart();

        public const string SessionKeyName = "_Name";
        public string SessionInfo_Name { get; private set; }

        public void OnGetAsync()
        {

        }
        public async Task<PartialViewResult> OnGetCartPartialAsync()
        {
            var userName = GetUserName();
            if (userName != null)
            {
                Cart = await _cartRepository.GetCartByUserName(userName);
            }
            return Partial("_ToCart", model: Cart);
        }
        private string GetUserName()
        {
            return HttpContext.Session.GetString(SessionKeyName);
        }
        public async Task OnPostRemoveItemAsync(int cartId, int cartItemId)
        {
            await _cartRepository.RemoveItem(cartId, cartItemId);                   
        }
        }
        }






我不熟悉 asp.net 核心,但我將展示我通常如何在不關注語法的情況下進行操作。

首先在視圖上不需要添加多個表單,但應該使用卡片 ID 作為索引和刪除按鈕發送選定的索引,如下所示:

@foreach (var item in Model.Items)
       {
          <div id="card_@item.cardId">
            <h4 class="text-left text-body">@item.Price.ToString("c")
            <button class="btn btn-sm" onclick="removeItem('@item.cardId') title="Trash"><i style="font-size:large" 
             class="text-warning icon-Trash"></i></button>
            </h4>
          </div>

       }

然后腳本函數將調用 remove api 並刪除選定的卡片,而無需重新渲染頁面:

<script type="text/javascript">
    function removeItem(cardId) {
        var removeUrl = "your apiUrl";
        $.post( "removeUrl", { cardId: cardId })
              .done(function( data ) {
                  alert( data ); //usually return true or false if true remove card
                  $('#card_'+ cardId).remove();
         });
    }
</script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM