【发布时间】:2018-11-26 14:00:01
【问题描述】:
我目前有这个观点:
但是每当我向购物车添加东西时,它都不会自动更新计数。仅在我刷新页面时。
我怎样才能让它自动更新?它在 _Layout 视图上有一个视图组件。
CartViewComponent
public class CartViewComponent : ViewComponent
{
private readonly ApplicationDbContext _context;
private readonly SignInManager<UserModel> _signInManager;
private readonly UserManager<UserModel> _userManager;
public CartViewComponent(
ApplicationDbContext context,
SignInManager<UserModel> signInManager,
UserManager<UserModel> userManager)
{
_context = context;
_signInManager = signInManager;
_userManager = userManager;
}
public int CheckIfOrderExists()
{
var userId = Request.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);
OrderMain orderMain = _context.OrderMains.Where(o => o.user_id == userId).FirstOrDefault();
if (orderMain != null)
{
return orderMain.id;
}
else
{
return 0;
}
}
public int CountItemsInShoppingCart(int order_id)
{
var result = (from orderlines in _context.OrderLines
join items in _context.Items on orderlines.item_id equals items.id
join ordermains in _context.OrderMains on orderlines.order_id equals ordermains.id
where orderlines.order_id == order_id
select orderlines).Count();
return result;
}
public IViewComponentResult Invoke()
{
int order_id = CheckIfOrderExists();
int count = CountItemsInShoppingCart(order_id);
ViewBag.count = count;
return View(ViewBag.count);
}
}
Default.cshtml
<span class="badge">@ViewBag.count</span>
_Layout.cshtml
...
<li>
<a asp-area="" asp-controller="ShoppingCart" asp-action="Index">
<span style="color:black;" class="glyphicon glyphicon-shopping-cart"></span>
@await Component.InvokeAsync("Cart")
</a>
</li>
...
【问题讨论】:
标签: c# html razor asp.net-core-mvc asp.net-core-viewcomponent