简体   繁体   English

@foreach 循环中的多种形式。 如何使用 javascript 异步提交一个。 C# 核心剃刀

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

Shopping cart with many items how to remove any item asynchronously with JavaScript this is my work so far.带有许多项目的购物车如何使用 JavaScript 异步删除任何项目这是我迄今为止的工作。 Can anyone improve on this?任何人都可以改进吗?

your help would be greatly appreciated.您的帮助将不胜感激。 Have a great day祝你有美好的一天

Ok so this works if you remove items from the top of the list but fails if you remove items from some other place.好的,如果您从列表顶部删除项目,则此方法有效,但如果您从其他位置删除项目,则失败。

The problem seems to be that the form names are all the same "remove" without any indexing.问题似乎是表单名称都是相同的“删除”而没有任何索引。

Problem is I'm not sure how to proceed with this.问题是我不确定如何进行。

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);                   
        }
        }
        }






I am not familiar with asp.net core, but I will show how I usually do it without focusing on syntax.我不熟悉 asp.net 核心,但我将展示我通常如何在不关注语法的情况下进行操作。

first on the view no need to add multiple form but should use card id as index and delete button sent selected index like this:首先在视图上不需要添加多个表单,但应该使用卡片 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>

       }

then the script function will call remove api and remove selected card with no need to re-render the page:然后脚本函数将调用 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