Meine Gruppe und ich haben uns Mühe gegeben, eine Antwort auf diese Frage für unsere Website zu finden, und wir haben endlich den Schritt getan, die Community um Hilfe zu bitten!ASP.NET MVC - Aus Warenkorb entfernen
Ziel ist es, den Button unserer Website zu "Entfernen aus dem Warenkorb" zu verknüpfen und die Datenbank auf 0 zurückzusetzen sowie die Seite zu aktualisieren und die stattfindende Dekrementierung anzuzeigen.
Das JavaScript der Warenkorb-Ansicht scheint nicht zu funktionieren, aber ich bin mir nicht sicher, ob dies letztendlich das Problem ist. Wir haben viele Anleitungen wie den MVC Music Store und ASP.NET-Dokumentationen befolgt.
Index.cshtml:
script src="/Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
// Document.ready -> link up remove event handler
$(".RemoveLink").click(function() {
// Get the id from the link
var recordToDelete = $(this).attr("data-id");
if (recordToDelete != '') {
// Perform the ajax post
$.post("/ShoppingCart/RemoveFromCart", { "id": recordToDelete },
function (data) {
// Successful requests get here
// Update the page elements
if (data.ItemCount == 0) {
$('#row-' + data.DeleteId).fadeOut('slow');
} else {
$('#item-count-' + data.DeleteId).text(data.ItemCount);
}
$('#cart-total').text(data.CartTotal);
$('#update-message').text(data.Message);
$('#cart-status').text('Cart (' + data.CartCount + ')');
});
}
});
});
function handleUpdate() {
// Load and deserialize the returned JSON data
var json = context.get_data();
var data = Sys.Serialization.JavaScriptSerializer.deserialize(json);
// Update the page elements
if (data.ItemCount == 0) {
$('#row-' + data.DeleteId).fadeOut('slow');
} else {
$('#item-count-' + data.DeleteId).text(data.ItemCount);
}
$('#cart-total').text(data.CartTotal);
$('#update-message').text(data.Message);
$('#cart-status').text('Cart (' + data.CartCount + ')');
}
</script>
<h3>
<em>Review</em> your cart:
</h3>
<div id="update-message">
</div>
<div style="height:600px; overflow:auto; padding-top: 50px; margin-left: 200px; width: 1050px; ">
<table id="cart-summary" border="1" frame="void" rules="rows" style="width:100%;margin-left:auto; margin-right: auto;">
<tr class="data-table">
<th colspan="1">
Item(s)
</th>
<th colspan="1" style="text-align:center;">
Price
</th>
<th colspan="1" style="text-align:center;">
Quantity
</th>
<th colspan="1" style="text-align:center;">
Total
</th>
<th></th>
</tr>
@foreach (var item in Model.CartItem)
{
<tr>
<td style="margin:auto;width:500px;">
<div style="float:left;">
<a [email protected](String.Format("~/Books/Details/{0}", item.Book.id))>
<img class="img-responsive" src="@Url.Content(String.Format("~/Content/img/books/{0}.jpg",item.Book.ISBN))" style="width: 100px; height: 150px;" />
</a>
</div>
<div style="margin-top:37px;">
<a [email protected](String.Format("~/Books/Details/{0}", item.Book.id))>
<span>@Html.DisplayFor(modelItem => item.Book.Title)</span><br />
</a>
<span style="text-align:left;">@Html.DisplayFor(modelItem => item.Book.Author)</span><br /><br />
<span style="text-align:left">ISBN: @Html.DisplayFor(modelItem => item.Book.ISBN)</span>
</div>
</td>
<td>
<p style="text-align:center;">@item.Book.PriceNew</p>
</td>
<td>
<p style="text-align:center;">@item.Quantity</p>
<a href="#" class="RemoveLink" data-id="@item.RecordId">Remove from cart</a>
<!--data-url='Url.Content("~/ShoppingCart/RemoveFromCart")'>
Remove from cart
</a>-->
</td>
<td>
<p>@Model.CartTotal</p>
</td>
</tr>
}
<tr>
<td></td>
<td>
<p style="padding-top:15px;"></p>
<br />
<button type="button">
@Html.ActionLink("Back to List", "../Books/Index")
</button>
</td>
<td></td>
<td id="cart-total">
<p style="padding-top: 10px;font-weight:bold;color:rgb(179,0,0);font-size:18px;">Subtotal: @Model.CartTotal</p>
<button type="button">
@Html.ActionLink("Checkout!", "AddressAndPayment", "Checkout")
</button>
</td>
</tr>
</table>
</div>
Der nächste Satz von Code ist der C# -Code. Cart.cs:
public int RemoveFromCart(int id)
{
var cartItem = bookDb.Carts.Single(
c => (c.CartId == ShoppingCartId)
&& c.RecordId == id);
int itemCount = 0;
if (cartItem != null)
{
if (cartItem.Quantity > 1)
{
cartItem.Quantity--;
itemCount = cartItem.Quantity;
}
else
{
bookDb.Carts.Remove(cartItem);
}
bookDb.SaveChanges();
}
return itemCount;
}
schließlich den MVC-Satz von Code zu vervollständigen, die miteinander in Beziehung stehen ... Wir glauben auch, es kann hier ein Fehler sein. Wir sind einfach nicht erfahren genug, um es zu wissen.
ShoppingCartController.cs:
// GET: ShoppingCart
public ActionResult Index()
{
var cart = ShoppingCart.GetCart(this.HttpContext);
// Set up our View Model
var viewModel = new ShoppingCartViewModel
{
CartItem = cart.GetCartItems(),
CartTotal = cart.GetTotal()
};
return View(viewModel);
}
// GET: Book/Details/5
// Button that allows you to add to the cart you will be redirected to the Shopping cart index page
public ActionResult AddToCart(string id)
{
var addedBook = bookdb.Books.Single(book => book.ISBN == id);
var cart = ShoppingCart.GetCart(this.HttpContext);
cart.AddToCart(addedBook);
bookdb.SaveChanges();
return RedirectToAction("Index");
}
// this is attached to the remove to cart button in the shopping cart index page, the index page will then reload
[HttpPost]
public ActionResult RemoveFromCart(int id)
{
// Retrieve the current user's shopping cart
var cart = ShoppingCart.GetCart(this.HttpContext);
// Get the name of the book to display confirmation
string bookName = bookdb.Carts.Single(book => book.RecordId == id).Book.Title;
// Remove from cart
int itemCount = cart.RemoveFromCart(id);
// Display confirmation message
var results = new ShoppingCartRemoveViewModel
{
Message = Server.HtmlEncode(bookName) + " has been removed from the shopping cart",
CartTotal = cart.GetTotal(),
CartCount = cart.GetCount(),
ItemCount = itemCount,
DeleteId = id
};
//return view();
return Json(results);
}
Dank einem Haufen!
Hallo! Kannst du eine Demo [hier] (https://dotnetfiddle.net/) erstellen? – karritos
Erfolgt das Entfernen des Elements wie erwartet auf der Serverseite, d. H. Wenn Sie diesen API-Endpunkt erreichen, wird das Element aus der Datenbank entfernt? –
Es ist, ich habe es endlich herausgefunden. Wenn Sie den ersten Codeblock bemerken, werden zwei Skripts angezeigt. Die zweite ist nicht richtig formatiert, weshalb die jQuery sozusagen "ignoriert" wurde. Dann musste ich die Zeile des Codes '@ Ajax.ActionLink (" Entfernen "," Index "," ShoppingCart ", neue {LoadingElementId = item.RecordId}, neue AjaxOptions {OnSuccess =" handleUpdate "}, neue {@) hinzufügen class = "RemoveLink", @ data_id = @ item.RecordId}), damit die Site erkennt, dass der Button/Link die jQuery-Funktionen ausführt. Ich habe geantwortet, falls jemand Probleme hat! Scheint ein häufiges Problem zu sein. –