@foreach循环中的多个表单.我如何提交一个异步与javascript.c#核心Razor &g



购物车与许多项目如何删除任何项目异步与JavaScript这是我的工作到目前为止。有人能改进一下吗?

非常感谢你的帮助。祝你有美好的一天

好的,如果你从列表的顶部删除项目,那么这个工作,但如果你从其他地方删除项目,则失败。

问题似乎是表单名称都是相同的"remove"没有任何索引

问题是我不知道该怎么做。

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);                   
}
}
}
Update 2
This is the modified code I used. This is the error in the console.
XML Parsing Error: no root element found Location: localhost:44331/sales/cart?handler=RemoveItem Line Number 1, Column 1
There is no error on the page just nothing happens on the click of the trash can.
<script type="text/javascript">
function removeItem(cartItemId, cardId) {
var removeUrl = "/sales/cart?handler=RemoveItem";
$.post(removeUrl,
{
cartItemId: cartItemId,
cardId: cardId
})
.done(function (data) {
alert(data); //usually return true or false if true 
remove card
$('#card_' + cardId).remove();
});
}
</script>


我不熟悉asp.net core,但我将展示我通常是如何做的,而不关注语法。

第一个视图不需要添加多个表单,但应该使用卡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>

相关内容