Беда...

This commit is contained in:
Илья Федотов 2024-05-31 16:05:43 +04:00
parent 5f4887ec8c
commit 979625ebae
14 changed files with 201 additions and 422 deletions

View File

@ -27,6 +27,15 @@ namespace ElectronicsShopBusinessLogic.BusinessLogic
_logger.LogInformation("Insert operation failed");
return false;
}
return true;
}
public bool Update(OrderBindingModel model) {
CheckModel(model);
if (_storage.Update(model) == null) {
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
@ -68,29 +77,5 @@ namespace ElectronicsShopBusinessLogic.BusinessLogic
_logger.LogInformation($"ReadElement find. ID:{element.ID}");
return element;
}
public bool AddProduct(IProductModel product, int count, int orderID) {
var _order = ReadElement(new OrderSearchModel { ID = orderID });
try {
if (_order.ProductList.ContainsKey(product.ID)) {
_order.ProductList[product.ID] = (product, count);
}
else {
_order.ProductList.Add(product.ID, (product, count));
_storage.Update(new OrderBindingModel {
ClientID = _order.ClientID,
ProductList = _order.ProductList,
Sum = 5000,
DateCreate = DateTime.Now,
ID = _order.ID,
});
}
}
catch {
_logger.LogWarning("AddProduct. operation is failed");
return false;
}
return true;
}
}
}

View File

@ -17,6 +17,6 @@ namespace ElectronicsShopContracts.BusinessLogicContracts
OrderViewModel? ReadElement(OrderSearchModel model);
bool CreateOrder(OrderBindingModel model);
bool AddProduct(IProductModel product, int count, int orderID);
bool Update(OrderBindingModel model);
}
}

View File

@ -27,13 +27,13 @@ namespace ElectronicsShopDataBaseImplement.Implements
using var context = new Database();
using var transcation = context.Database.BeginTransaction();
try {
var product = context.Orders.FirstOrDefault(rec => rec.ID == model.ID);
if (product == null) {
var order = context.Orders.FirstOrDefault(rec => rec.ID == model.ID);
if (order == null) {
return null;
}
product.UpdateProducts(context, model);
order.UpdateProducts(context, model);
transcation.Commit();
return product.GetViewModel;
return order.GetViewModel;
}
catch {
transcation.Rollback();
@ -61,7 +61,8 @@ namespace ElectronicsShopDataBaseImplement.Implements
.Include(x => x.Payments)
.Include(x => x.Products)
.ThenInclude(x => x._product)
.FirstOrDefault(x => (model.ClientID.HasValue && x.ClientID == model.ClientID))?.GetViewModel;
.OrderBy(x => x.ID)
.LastOrDefault(x => (model.ClientID.HasValue && x.ClientID == model.ClientID))?.GetViewModel;
}
if (model.ID.HasValue)
{
@ -77,7 +78,7 @@ namespace ElectronicsShopDataBaseImplement.Implements
public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{
using var context = new Database();
if (!model.ID.HasValue && (model.DateFrom == null || model.DateTo == null))
if (!model.ID.HasValue && model.DateFrom.HasValue && model.DateTo.HasValue)
{
return new();
}

View File

@ -1,283 +0,0 @@
// <auto-generated />
using System;
using ElectronicsShopDataBaseImplement;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace ElectronicsShopDataBaseImplement.Migrations
{
[DbContext(typeof(Database))]
[Migration("20240529092847_Init")]
partial class Init
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "8.0.4")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("ElectronicsShopDataBaseImplement.Models.Client", b =>
{
b.Property<int>("ID")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("ID"));
b.Property<string>("ClientFIO")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Email")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("ID");
b.ToTable("Clients");
});
modelBuilder.Entity("ElectronicsShopDataBaseImplement.Models.CostItem", b =>
{
b.Property<int>("ID")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("ID"));
b.Property<int>("CostNum")
.HasColumnType("int");
b.Property<int>("EmployeeID")
.HasColumnType("int");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<double>("Price")
.HasColumnType("float");
b.HasKey("ID");
b.HasIndex("EmployeeID");
b.ToTable("CostItems");
});
modelBuilder.Entity("ElectronicsShopDataBaseImplement.Models.Employee", b =>
{
b.Property<int>("ID")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("ID"));
b.Property<string>("EmployeeFIO")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Login")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("ID");
b.ToTable("Employees");
});
modelBuilder.Entity("ElectronicsShopDataBaseImplement.Models.Order", b =>
{
b.Property<int>("ID")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("ID"));
b.Property<int>("ClientID")
.HasColumnType("int");
b.Property<DateTime>("DateCreate")
.HasColumnType("datetime2");
b.Property<double>("Sum")
.HasColumnType("float");
b.HasKey("ID");
b.HasIndex("ClientID");
b.ToTable("Orders");
});
modelBuilder.Entity("ElectronicsShopDataBaseImplement.Models.OrderProduct", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("Count")
.HasColumnType("int");
b.Property<int>("OrderID")
.HasColumnType("int");
b.Property<int>("ProductID")
.HasColumnType("int");
b.Property<int?>("_productID")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ProductID");
b.HasIndex("_productID");
b.ToTable("OrderProducts");
});
modelBuilder.Entity("ElectronicsShopDataBaseImplement.Models.Paymeant", b =>
{
b.Property<int>("ID")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("ID"));
b.Property<int>("OrderID")
.HasColumnType("int");
b.Property<int>("PayOption")
.HasColumnType("int");
b.Property<int?>("PaymentID")
.HasColumnType("int");
b.Property<int>("ProductID")
.HasColumnType("int");
b.Property<double>("SumPayment")
.HasColumnType("float");
b.HasKey("ID");
b.HasIndex("PaymentID");
b.ToTable("Paymeants");
});
modelBuilder.Entity("ElectronicsShopDataBaseImplement.Models.Product", b =>
{
b.Property<int>("ID")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("ID"));
b.Property<int>("CostItemID")
.HasColumnType("int");
b.Property<double>("Price")
.HasColumnType("float");
b.Property<string>("ProductName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("ID");
b.HasIndex("CostItemID");
b.ToTable("Products");
});
modelBuilder.Entity("ElectronicsShopDataBaseImplement.Models.CostItem", b =>
{
b.HasOne("ElectronicsShopDataBaseImplement.Models.Employee", "Employee")
.WithMany()
.HasForeignKey("EmployeeID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Employee");
});
modelBuilder.Entity("ElectronicsShopDataBaseImplement.Models.Order", b =>
{
b.HasOne("ElectronicsShopDataBaseImplement.Models.Client", null)
.WithMany("Orders")
.HasForeignKey("ClientID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("ElectronicsShopDataBaseImplement.Models.OrderProduct", b =>
{
b.HasOne("ElectronicsShopDataBaseImplement.Models.Order", "_order")
.WithMany("Products")
.HasForeignKey("ProductID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("ElectronicsShopDataBaseImplement.Models.Product", "_product")
.WithMany()
.HasForeignKey("_productID");
b.Navigation("_order");
b.Navigation("_product");
});
modelBuilder.Entity("ElectronicsShopDataBaseImplement.Models.Paymeant", b =>
{
b.HasOne("ElectronicsShopDataBaseImplement.Models.Order", null)
.WithMany("Payments")
.HasForeignKey("PaymentID");
});
modelBuilder.Entity("ElectronicsShopDataBaseImplement.Models.Product", b =>
{
b.HasOne("ElectronicsShopDataBaseImplement.Models.CostItem", "CostItem")
.WithMany()
.HasForeignKey("CostItemID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("CostItem");
});
modelBuilder.Entity("ElectronicsShopDataBaseImplement.Models.Client", b =>
{
b.Navigation("Orders");
});
modelBuilder.Entity("ElectronicsShopDataBaseImplement.Models.Order", b =>
{
b.Navigation("Payments");
b.Navigation("Products");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -1,48 +0,0 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace ElectronicsShopDataBaseImplement.Migrations
{
/// <inheritdoc />
public partial class AddMessages : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Messages",
columns: table => new
{
MessageID = table.Column<string>(type: "nvarchar(450)", nullable: false),
ClientID = table.Column<int>(type: "int", nullable: true),
SenderName = table.Column<string>(type: "nvarchar(max)", nullable: false),
DateDelivery = table.Column<DateTime>(type: "datetime2", nullable: false),
Subject = table.Column<string>(type: "nvarchar(max)", nullable: false),
Body = table.Column<string>(type: "nvarchar(max)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Messages", x => x.MessageID);
table.ForeignKey(
name: "FK_Messages_Clients_ClientID",
column: x => x.ClientID,
principalTable: "Clients",
principalColumn: "ID");
});
migrationBuilder.CreateIndex(
name: "IX_Messages_ClientID",
table: "Messages",
column: "ClientID");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Messages");
}
}
}

View File

@ -12,8 +12,8 @@ using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace ElectronicsShopDataBaseImplement.Migrations
{
[DbContext(typeof(Database))]
[Migration("20240530150159_AddMessages")]
partial class AddMessages
[Migration("20240531061328_InitMigration")]
partial class InitMigration
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
@ -174,14 +174,11 @@ namespace ElectronicsShopDataBaseImplement.Migrations
b.Property<int>("ProductID")
.HasColumnType("int");
b.Property<int?>("_productID")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ProductID");
b.HasIndex("OrderID");
b.HasIndex("_productID");
b.HasIndex("ProductID");
b.ToTable("OrderProducts");
});
@ -274,13 +271,15 @@ namespace ElectronicsShopDataBaseImplement.Migrations
{
b.HasOne("ElectronicsShopDataBaseImplement.Models.Order", "_order")
.WithMany("Products")
.HasForeignKey("ProductID")
.HasForeignKey("OrderID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("ElectronicsShopDataBaseImplement.Models.Product", "_product")
.WithMany()
.HasForeignKey("_productID");
.HasForeignKey("ProductID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("_order");

View File

@ -6,7 +6,7 @@ using Microsoft.EntityFrameworkCore.Migrations;
namespace ElectronicsShopDataBaseImplement.Migrations
{
/// <inheritdoc />
public partial class Init : Migration
public partial class InitMigration : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
@ -41,6 +41,27 @@ namespace ElectronicsShopDataBaseImplement.Migrations
table.PrimaryKey("PK_Employees", x => x.ID);
});
migrationBuilder.CreateTable(
name: "Messages",
columns: table => new
{
MessageID = table.Column<string>(type: "nvarchar(450)", nullable: false),
ClientID = table.Column<int>(type: "int", nullable: true),
SenderName = table.Column<string>(type: "nvarchar(max)", nullable: false),
DateDelivery = table.Column<DateTime>(type: "datetime2", nullable: false),
Subject = table.Column<string>(type: "nvarchar(max)", nullable: false),
Body = table.Column<string>(type: "nvarchar(max)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Messages", x => x.MessageID);
table.ForeignKey(
name: "FK_Messages_Clients_ClientID",
column: x => x.ClientID,
principalTable: "Clients",
principalColumn: "ID");
});
migrationBuilder.CreateTable(
name: "Orders",
columns: table => new
@ -135,23 +156,23 @@ namespace ElectronicsShopDataBaseImplement.Migrations
.Annotation("SqlServer:Identity", "1, 1"),
OrderID = table.Column<int>(type: "int", nullable: false),
ProductID = table.Column<int>(type: "int", nullable: false),
Count = table.Column<int>(type: "int", nullable: false),
_productID = table.Column<int>(type: "int", nullable: true)
Count = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_OrderProducts", x => x.Id);
table.ForeignKey(
name: "FK_OrderProducts_Orders_ProductID",
column: x => x.ProductID,
name: "FK_OrderProducts_Orders_OrderID",
column: x => x.OrderID,
principalTable: "Orders",
principalColumn: "ID",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_OrderProducts_Products__productID",
column: x => x._productID,
name: "FK_OrderProducts_Products_ProductID",
column: x => x.ProductID,
principalTable: "Products",
principalColumn: "ID");
principalColumn: "ID",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
@ -160,9 +181,14 @@ namespace ElectronicsShopDataBaseImplement.Migrations
column: "EmployeeID");
migrationBuilder.CreateIndex(
name: "IX_OrderProducts__productID",
name: "IX_Messages_ClientID",
table: "Messages",
column: "ClientID");
migrationBuilder.CreateIndex(
name: "IX_OrderProducts_OrderID",
table: "OrderProducts",
column: "_productID");
column: "OrderID");
migrationBuilder.CreateIndex(
name: "IX_OrderProducts_ProductID",
@ -188,6 +214,9 @@ namespace ElectronicsShopDataBaseImplement.Migrations
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Messages");
migrationBuilder.DropTable(
name: "OrderProducts");

View File

@ -171,14 +171,11 @@ namespace ElectronicsShopDataBaseImplement.Migrations
b.Property<int>("ProductID")
.HasColumnType("int");
b.Property<int?>("_productID")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ProductID");
b.HasIndex("OrderID");
b.HasIndex("_productID");
b.HasIndex("ProductID");
b.ToTable("OrderProducts");
});
@ -271,13 +268,15 @@ namespace ElectronicsShopDataBaseImplement.Migrations
{
b.HasOne("ElectronicsShopDataBaseImplement.Models.Order", "_order")
.WithMany("Products")
.HasForeignKey("ProductID")
.HasForeignKey("OrderID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("ElectronicsShopDataBaseImplement.Models.Product", "_product")
.WithMany()
.HasForeignKey("_productID");
.HasForeignKey("ProductID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("_order");

View File

@ -40,7 +40,7 @@ namespace ElectronicsShopDataBaseImplement.Models
}
}
[ForeignKey("ProductID")]
[ForeignKey("OrderID")]
public virtual List<OrderProduct> Products { get; set; } = new();
[ForeignKey("PaymentID")]
@ -72,10 +72,11 @@ namespace ElectronicsShopDataBaseImplement.Models
ClientID = ClientID,
Sum = Sum,
DateCreate = DateCreate,
ProductList = ProductList,
};
public void UpdateProducts(Database context,OrderBindingModel model) {
var orderProducts = context.OrderProducts.Where(rec => rec.ProductID == model.ID).ToList();
var orderProducts = context.OrderProducts.Where(rec => rec.OrderID == model.ID).ToList();
if (orderProducts != null && orderProducts.Count > 0) {
context.OrderProducts.RemoveRange(orderProducts.Where(rec => !model.ProductList.ContainsKey(rec.ProductID)));
context.SaveChanges();
@ -85,7 +86,7 @@ namespace ElectronicsShopDataBaseImplement.Models
}
context.SaveChanges();
}
var order = context.Orders.First(x => x.ID == ID);
var order = context.Orders.First(x => x.ID == model.ID);
foreach (var op in model.ProductList) {
context.OrderProducts.Add(new OrderProduct {
_order = order,

View File

@ -12,8 +12,10 @@ namespace ElectronicsShopDataBaseImplement.Models
{
public int Id { get; set; }
[Required]
public int OrderID { get; set; }
[Required]
public int ProductID { get; set; }
[Required]

View File

@ -56,7 +56,7 @@ namespace ElectronicsShopDataBaseImplement.Models
ProductName = ProductName,
Price = Price,
CostItemID = CostItemID,
CostItemName = CostItem.Name
CostItemName = CostItem?.Name
};
}
}

View File

@ -2,9 +2,11 @@
using ElectronicsShopContracts.BusinessLogicContracts;
using ElectronicsShopContracts.SearchModels;
using ElectronicsShopContracts.ViewModels;
using ElectronicsShopDataBaseImplement;
using ElectronicsShopDataBaseImplement.Models;
using ElectronicsShopDataModels.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
namespace ElectronicsShopRestAPI.Controllers {
@ -18,11 +20,14 @@ namespace ElectronicsShopRestAPI.Controllers {
private readonly IOrderLogic _order;
private readonly IMessageInfoLogic _message;
private Dictionary<int, (IProductModel, int)> _productlist;
public MainController(ILogger<MainController> logger, IProductLogic product,
IOrderLogic orderLogic) {
_logger = logger;
_product = product;
_order = orderLogic;
_productlist = new Dictionary<int, (IProductModel, int)>();
}
[HttpGet]
@ -89,6 +94,28 @@ namespace ElectronicsShopRestAPI.Controllers {
}
}
[HttpGet]
public List<List<string>> GetOrderProducts(int _orderid) {
var list = new List<List<string>>();
try {
var products = _order.ReadElement(new OrderSearchModel { ID = _orderid});
foreach (var pr in products.ProductList) {
var sentence = new List<string> {
JsonConvert.SerializeObject(pr.Value.Item1),
JsonConvert.SerializeObject(pr.Value.Item2.ToString())
};
list.Add(sentence);
}
return list;
}
catch (Exception ex) {
_logger.LogError(ex, "Ошибка получения списка товаров");
throw;
}
}
[HttpPost]
public void AddProduct(List<string> jslist)
{
@ -96,11 +123,39 @@ namespace ElectronicsShopRestAPI.Controllers {
int count = JsonConvert.DeserializeObject<int>(jslist[1]);
int orderid = JsonConvert.DeserializeObject<int>(jslist[2]);
var view = _order.ReadElement(new OrderSearchModel { ID = orderid });
if (view != null) {
_productlist = view.ProductList;
}
_logger.LogInformation($"Добавление нового товара: {product.ProductName} - {count}");
if (_productlist.ContainsKey(product.ID)) {
_productlist[product.ID] = (product, count);
}
else {
_productlist.Add(product.ID, (product, count));
}
if (_productlist == null || _productlist.Count == 0) {
_logger.LogInformation("Корзина пуста, ошибка");
}
_logger.LogInformation("Сохранение Заказа");
try {
_order.AddProduct(product, count, orderid);
var model = new OrderBindingModel {
ID = orderid,
ClientID = view.ClientID,
DateCreate = view.DateCreate,
ProductList = _productlist
};
var operationResult = _order.Update(model);
if (!operationResult) {
throw new Exception("Ошибка при сохранении, дополнительная информация в логах");
}
}
catch (Exception ex) {
_logger.LogError(ex, "Ошибка добавления заказа");
_logger.LogError(ex, "Ошибка добавления товара");
throw;
}
}

View File

@ -5,9 +5,11 @@ using ElectronicsShopContracts.ViewModels;
using ElectronicsShopDataModels.Models;
using ElectronicsShopUserApp.Models;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.Serialization;
using System.Xml.Serialization;
namespace ElectronicsShopUserApp.Controllers {
public class HomeController : Controller {
@ -18,6 +20,7 @@ namespace ElectronicsShopUserApp.Controllers {
public HomeController(ILogger<HomeController> logger/*, IOrderLogic orderLogic*/) {
_logger = logger;
//_order = orderLogic;
_productList = new Dictionary<int, (IProductModel, int)>();
}
public IActionResult Index() {
@ -101,8 +104,9 @@ namespace ElectronicsShopUserApp.Controllers {
return Redirect("~/Home/Enter");
}
var view = APIClient.GetRequset<List<OrderViewModel>>($"api/main/getorders?_clientid={APIClient.Client.ID}");
return View(APIClient.GetRequset<List<OrderViewModel>>($"api/main/getorders?_clientid={APIClient.Client.ID}"));
return View(view);
}
[HttpGet]
@ -123,8 +127,20 @@ namespace ElectronicsShopUserApp.Controllers {
return Redirect("~/Home/Enter");
}
var view = APIClient.GetRequset<OrderViewModel>($"api/main/getorder?_clientid={APIClient.Client?.ID}");
var products = APIClient.GetRequset<List<List<string>>>($"api/main/getorderproducts?_orderid={view?.ID}");
return View(view);
foreach (var pr in products) {
var product = JsonConvert.DeserializeObject<ProductViewModel>(pr[0]);
int count = JsonConvert.DeserializeObject<int>(pr[1]);
_productList.Add(product.ID, (product, count));
}
return View(_productList);
}
[HttpPost]
public void OrderView(int sum) {
Response.Redirect("Orders");
}
[HttpGet]
@ -142,16 +158,6 @@ namespace ElectronicsShopUserApp.Controllers {
Response.Redirect("OrderView");
}
[HttpPost]
private double CalcAll(Dictionary<int, (IProductModel, int)> ProductList)
{
Double Sum = 0;
foreach (var ProductItem in ProductList)
{
Sum += (ProductItem.Value.Item1.Price * ProductItem.Value.Item2);
}
return Sum;
}
[HttpPost]
public double Calc(int count, int product)
{

View File

@ -1,6 +1,7 @@
@using ElectronicsShopContracts.ViewModels
@using ElectronicsShopDataModels.Models
@model OrderViewModel
@model Dictionary<int, (IProductModel, int)>
@{
ViewData["Title"] = "OrderView";
@ -10,11 +11,12 @@
<h1 class="display-4">Создание корзины</h1>
</div>
<form method="post">
<div class=" text-center">
<div class="row">
<label class="col-4">Номер корзины:</label>
<div class="col-4">Сумма:</div>
<div class="col-8">
<input id="OrderID" class="form-control" type="text" name="OrderID" value="@Model.ID" readonly />
<input id="sum" type="text" name="sum" readonly />
</div>
</div>
<p>
@ -35,22 +37,53 @@
</tr>
</thead>
<tbody>
@foreach (var item in Model.ProductList) {
<tr>
@foreach (var item in Model) {
<tr class="element">
<th>
@Html.DisplayFor(modelItem => item.Value.Item1.ProductName);
@Html.DisplayFor(modelItem => item.Value.Item1.ProductName)
</th>
<th>
@Html.DisplayFor(modelItem => item.Value.Item2);
<th class="count">
@Html.DisplayFor(modelItem => item.Value.Item2)
</th>
<th>
@Html.DisplayFor(modelItem => (item.Value.Item1.Price * item.Value.Item2));
<th class="countsum">
@Html.DisplayFor(modelItem => item.Value.Item1.Price)
</th>
<td>
<a class="btn btn-primary btn-sm" asp-action="DeleteProductOrder" asp-></a>
<a class="btn btn-primary btn-sm" asp-action="DeleteProductOrder" asp->Удалить</a>
</td>
</tr>
}
</tbody>
</table>
<div class="row">
<div class="col-4"></div>
<div class="col-8">
<input type="submit" value="Заказ готова, вернуться!" class="btn btn-primary" />
</div>
</div>
</div>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
</form>
<script>
$('btn').on('click', function () {
calc();
});
let sum = 0;
const elementRows = document.querySelectorAll('.element');
calc();
function calc() {
elementRows.forEach(row => {
const count = parseInt(row.querySelector('.count').innerHTML, 10);
const countsum = parseInt(row.querySelector('.countsum').innerHTML, 10);
const rowTotal = count * countsum;
sum += rowTotal;
});
$('#sum').val(sum);
}
</script>