asp.net mvc - добавить в корзину - PullRequest
0 голосов
/ 01 июня 2018

Допустим, у меня есть эта модель

public class Book
{
    public int Id { get; set; }
    public string Title { get; set; }
    public decimal Price { get; set; }
}

Может кто-нибудь объяснить мне, какой самый простой способ положить эти объекты в корзину и сделать заказ?

1 Ответ

0 голосов
/ 01 июня 2018

Есть много способов достичь своей цели.Вот один из подходов:

public class Book
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public decimal Price { get; set; }
    }

    public class CartItem
    {
        public Book Book { get; set;}
        public int Quantity { get; set;}
    }

    public class Order 
    {
        public List<CartItem> CartItems { get; set;}
        public int OrderNumber { get; set;}
        public decimal OrderTotal { get; set;}
    }

Затем вы можете добавить книги в корзину (корзина List<CartItems>), которая содержится в заказе.

Для демонстрации рассмотрим:

var book = new Book{ Id = 123, Title = "Hello World", Price = 42.42M };
var cartItem = new CartItem{ Book = book, Quantity = 2 };
var order = new Order{OrderNumber = 66};
order.CartItems = new List<CartItem>(); 
order.CartItems.Add(cartItem);

Console.WriteLine();

foreach(var item in order.CartItems)
{
    Console.WriteLine("Book ID: " + item.Book.Id);
    Console.WriteLine("Book Title: " + item.Book.Title);
    Console.WriteLine("Book Price: " + item.Book.Price);
    Console.WriteLine("Quantity: " + item.Quantity);
    Console.WriteLine("SubTotal: " + item.Quantity * item.Book.Price);
    order.OrderTotal += item.Quantity * item.Book.Price;
}   

Console.WriteLine("Order Total: " + order.OrderTotal);

Демо здесь: https://dotnetfiddle.net/qpi1ku

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...