2015-07-25 2 views
0

Я пытаюсь разрешить человеку удалять элементы из своей корзины с помощью jQuery и AJAX. Всякий раз, когда я нажимаю ссылку для удаления элемента, я получаю внутреннюю ошибку сервера 500. Вот мой код:500 (Внутренняя ошибка сервера) с jQuery

@model AccessorizeForLess.ViewModels.OrderDetailViewModel 

@{ 
    ViewBag.Title = "Index"; 
    Layout = "~/Views/Shared/_Layout.cshtml"; 
    } 
<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("/Orders/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 + ')'); 
        }); 
      } 
     }); 
    }); 
</script> 
<h3> 
    <em>Review</em> your cart: 
</h3> 
@*<p class="button"> 
    @Html.ActionLink("Checkout 
>>", "AddressAndPayment", "Checkout") 
</p>*@ 
<div id="update-message"> 
</div> 
<table> 
    <tr> 
     <th> 
      Product Name 
     </th> 
     <th>&nbsp;</th> 
     <th> 
      Price (each) 
     </th> 
     <td>&nbsp;</td> 
     <th> 
      Quantity 
     </th> 
     <th></th> 
    </tr> 
    @foreach (var item in Model.OrderItems) 
    { 
     <tr id="[email protected]"> 
      <td> 
       @Html.ActionLink(item.Product.ProductName, "Details", "Products", new { id = item.ProductId }, null) 
      </td> 
      <td>&nbsp;</td> 
      <td> 
       @item.ProductPrice 
      </td> 
      <td>&nbsp;</td> 
      <td id="[email protected]"> 
       @item.ProductQuantity 
      </td> 
      <td>&nbsp;</td> 
      <td> 
       <a href="#" class="RemoveLink" data-id="@item.ProductId">Remove</a> 
      </td> 
     </tr> 
    } 
    <tr> 
     <td> 
      Total 
     </td> 
     <td></td> 
     <td></td> 
     <td id="cart-total"> 
      @Model.OrderTotal 
     </td> 
    </tr> 
</table> 

EDIT

Вот код для метода Снимать в контроллере:

[HttpPost] 
public ActionResult RemoveFromCart(int id) 
{ 
    // Remove the item from the cart 
    var cart = ShoppingCart.GetCart(this.HttpContext); 

    // Get the name of the product to display confirmation 
    string productName = db.OrderItems 
     .FirstOrDefault(item => item.ProductId == id).Product.ProductName; 

    // Remove from cart 
    int itemCount = cart.RemoveFromCart(id); 

    // Display the confirmation message 
    var results = new ShoppingCartRemoveViewModel 
    { 
     Message = Server.HtmlEncode(productName) + 
      " has been removed from your shopping cart.", 
     CartTotal = cart.GetTotal(), 
     CartCount = cart.GetCount(), 
     ItemCount = itemCount, 
     DeleteId = id 
    }; 
    return Json(results); 
} 

Вот код для RemoveFromCart ссылки в предыдущий метод:

public int RemoveFromCart(int id) 
{ 
    // Get the cart 
    var cartItem = entities.Orders.FirstOrDefault(
     c => c.OrderGUID == ShoppingCartId 
     && c.OrderItems.Where(p => p.ProductId == id).FirstOrDefault().ProductId == id); 

    int itemCount = 0; 
    int? cartItemConut = cartItem.OrderItems.Where(p => p.ProductId == id).FirstOrDefault().ProductQuantity; 
    if (cartItem != null) 
    { 
     if (cartItemConut > 1) 
     { 
      cartItemConut--; 
      itemCount = (int)cartItemConut; 
     } 
     else 
     { 
      OrderItem oi = cartItem.OrderItems.Where(x => x.ProductId == id).FirstOrDefault(); 
      entities.OrderItems.Remove(oi); 
     } 
     // Save changes 
     entities.SaveChanges(); 
    } 
    return itemCount; 
} 

Вот код для ShoppingCartRemoveViewModel

using System.ComponentModel.DataAnnotations; 

namespace AccessorizeForLess.ViewModels 
{ 
    public class ShoppingCartRemoveViewModel 
    { 
     public string Message { get; set; } 
     [DisplayFormat(DataFormatString = "{0:C}")] 
     public decimal CartTotal { get; set; } 
     public int CartCount { get; set; } 
     public int ItemCount { get; set; } 
     public int DeleteId { get; set; } 
    } 
} 

Позволь мне знать, если вам нужно больше

+1

проверить консоль (f12) по запросу и сообщить нам, что это серверная сторона в любом случае (разрешения) – Pogrindis

+0

Все, что он говорит, это 500 (Внутренняя ошибка сервера) в консоли – PsychoCoder

+0

Вам действительно нужно посмотреть на свою серверную сторону журналы. – jmar777

ответ

0

Это была ошибка разрешения, пошла и дала разрешение учетной записи ASPNET на папке контроллеров и ошибка пошла далеко.

0

Ошибка сервера 500 означает, что в вашем коде было исключение. Я угадываю из вашего кода, что cartitem или oi (orderitem) имеет значение null, и вы пытались выполнить запрос LINQ к ним. Сначала проверьте, имеют ли они значение null, прежде чем пытаться выполнить запрос.

Смежные вопросы