在 mvc 中使用来自 3 个数据库表的过滤数据

use filtered data from 3 tables of database in mvc

我有(客户,客户最爱,产品)tables。在客户最喜欢的 table 中,我存储了客户 ID 和 PorductID,这表明哪个产品是哪个客户的最爱。我想在页面中显示所有产品(带有空心图标),如果客户有最喜欢的产品,该产品的图标应该是填充的心形图标。

这是我的代码:

控制器:

public ActionResult Index()
{
    ProductRepository BlProduct = new ProductRepository();
    CustomerRepository BlCustomer = new CustomerRepository();
    CustomerLikeRepository BlCusLike = new CustomerLikeRepository();
    var username = User.Identity.Name;
    var customer = BlCustomer.Where(x => x.Email == username).SingleOrDefault();
    var model = new HomeIndexViewModel();
    model.Products = BlProduct.Select();
    if(customer!=null)
    {
        model.Customer = customer;
        model.CostumerLikes = BlCusLike.Where(l=>l.CustomerId==customer.id).ToList();
    }
    return View(model);
}

ViewModel:

public class HomeIndexViewModel
{
    public IEnumerable<MySIte.Models.DomainModels.Product> Products { get; set; }
    public MySIte.Models.DomainModels.Customer Customer { get; set; }
    public IEnumerable<MySIte.Models.DomainModels.CostumersLike> CostumerLikes { get; set; }
}

查看:

@foreach (var item in Model.Products)
{
    <div class="product-thumb clearfix" style="height:100%;">
        <a href="@item.id">
        @Html.ImageFor(modelItem => item.ImgUrl, new { width = "500" }, "Tulips.jpg", "Files", "UploadImages")
        </a>
        </div>
        <div class="product-info clearfix">
            <span class="product-title">@item.Name</span>
            <div class="price">
                <del>
                    <span class="regular">$@item.Price.ToPrice()</span>
                </del>
                <ins>
                    <span class="amount">$@item.Price</span>
                </ins>
            </div>
        </div>
        <div class="add-to-cart text-center">
            <a data-toggle="modal" data-target="#@item.id"><i class="fa fa-search"></i>  quick  view</a>
        </div>
        @if (Model.Customer.Email==User.Identity.Name)
        { 
            <a href="#" class="addWish like" data-product="@item.id"><i class="fa fa-heart-o" style="color:red;"></i></a>
        }
    </li>
}

在视图部分有一个 IF 语句。那是我想将图标更改为 "fa-heart" 的地方,如果它是客户的最爱。

如何获取 Customerslike 数据并检查 customerid 和产品 id 在 table 中是否可用?

我终于知道如何检查 customerid 和 productid 是否存在于 customerliked table 中。

鉴于我必须像下面这样写 if 语句:

"if" 部分视图:

@if (Model.Customer.Email == User.Identity.Name)
{
    if (Model.CostumerLikes.Where(x => x.ProductId == item.id && x.CustomerId== Model.Customer.id).Count()==1)
    {
        <a href="#" class="addWish like" data-product="@item.id" data-user="@Model.Customer.id">
            <i class="fa fa-heart" style="color:red;"></i>
        </a>
    }
       else
    {
        <a href="#" class="addWish like" data-product="@item.id"  data-user="@Model.Customer.id">
            <i class="fa fa-heart-o" style="color:red;"></i>
        </a>
    }
}