在Views/Shared/Components目錄,再新增CartList目錄,最後加上Default.cshtml,也就是之前繼承ViewComponent的CartList.cs會回傳的頁面,主要是顯示購物車的內容:
@model WebMvc.Models.CartModels.Cart
@{
ViewData["Title"] = "My Cart";
}
<div class="container-fluid">
@if (TempData.ContainsKey("CartInoperativeMsg"))
{
<br />
<div class="alert alert-warning" role="alert">
@TempData["CartInoperativeMsg"]
</div>
}
else
{
<div class="nes-table-responsive">
<table class="nes-table is-bordered">
<thead>
<tr>
<th>Picture</th>
<th>Product</th>
<th>Price</th>
<th>Quantity</th>
<th>Cost</th>
</tr>
</thead>
<tbody>
@for (int i = 0; i < Model.Items.Count; i++)
{
var item = Model.Items[i];
<tr>
<td><img class="" src="@item.PictureUrl" /></td>
<td>@item.ProductName</td>
<td>$ @item.UnitPrice.ToString("N2")</td>
<td>
<input type="hidden" name="@("quantities[" + i + "].Key")" value="@item.Id" />
<input type="number" class="" min="1" name="@("quantities[" + i + "].Value")" value="@item.Quantity" />
</td>
<td>
$ @Math.Round(item.Quantity * item.UnitPrice, 2).ToString("N2")
@if (item.OldUnitPrice != 0)
{
<div class="alert alert-warning" role="alert"> Note that the price of this product changed in our Catalog. The old price when you originally added it to the cart was $ @item.OldUnitPrice </div>
}
</td>
</tr>
}
</tbody>
</table>
</div>
<div class="container">
<article class="row">
<section class="col-xs-10"></section>
<section class="col-xs-2">Total</section>
</article>
<article class="row">
<section class="col-xs-10"></section>
<section class="col-xs-2">$ @Model.Total()</section>
</article>
<article class="row">
<section class="col-xs-7"></section>
<section class="col-xs-2">
<button class="nes-btn is-primary" name="name" value="" type="submit">Update</button>
</section>
<section class="col-xs-3">
<input type="submit" class="nes-btn is-success" value="Checkout" name="action" />
</section>
</article>
</div>
}
</div>
在Views新增Cart目錄,再新增Index.cshtml,呼叫CartList ViewComponent和回前頁的共通Header:
@using WebMvc.Services
@using WebMvc.ViewModels
@inject IAuthService<ApplicationUser> authService
@{
ViewData["Title"] = "My Cart";
}
<form method="post" id="cartForm">
<div class="">
@await Html.PartialAsync("_Header", new List<Header>()
{
new Header(){Controller = "Catalog", Text = "Back to catalog"}
})
@await Component.InvokeAsync("CartList", new { user = authService.Get(User)})
</div>
</form>
在ViewModels新增Header.cs,指定要回到某一個Controller/顯示文字的共通模型:
namespace WebMvc.ViewModels
{
public class Header
{
public string Controller { get; set; }
public string Text { get; set; }
}
}
用VS執行所有3種Web Api和WebMvc,在用Dokcer執行cart.data和mssqlserver 2個服務,在首頁點Add to cart,將會把商品加入到購物車,並在購物車頁面可以修改數量,如圖1
圖1