Aytac
Aytac

Reputation: 335

How to display only one image in the view from multiple images on the database? (ASP.NET MVC)

I have multiple images for one product on the database. I created two tables. One for Products and another for Photos of products. And I want to show only one photo on the page. My code is below. I have tried to declare variable in the view. But there is error:

PhotoProduct' is a type, which is not valid in the given context

Is there other way for that?

Here is my code:

@foreach (Product prd in Model.Prod.Where(i => i.userid == Model.userr.ID))
{
    <div class="col-md-4">
    <figure class="card card-product mehsul">
    @PhotoProduct prphoto = Model.Photopr.Where(ph => ph.Product.id == ph.id).Take(1).ToList()
    {
        <div class="img-wrap"> <img class="img-fluid mehsulimg" src="@prphoto.Photo" alt=""> </div>
    }
    <div class="handhover">
    <img class="img-fluid" src="~/PublicFront/images/serv2b712.jpg" alt="">
    </div>
    <figcaption class="info-wrap">
        <h4 class="title">@prd.ProdName</h4>
        <p class="@prd.Price"></p>
    </figcaption>
    <div class="bottom-wrap">
        <a href="" class="btn btn-sm btn-primary float-right">Order Now</a>
        <div class="price-wrap h5">
            <span class="price-new">$1280</span> 
            <del class="price-old">$1980</del>
        </div> <!-- price-wrap.// -->
    </div> <!-- bottom-wrap.// -->
</figure>
</div> <!-- col // -->
}  

Upvotes: 1

Views: 518

Answers (1)

Jerdine Sabio
Jerdine Sabio

Reputation: 6185

I saw your models in this question before Error: Value cannot be null. Parameter name: source.

In your Photo Model you are already declaring PhotoProducts as virtual; public virtual ICollection<PhotoProduct> PhotoProducts { get; set; }

Using virtual in EntityFramework means that you are "lazy-loading" that entity or that entity gets automatically loaded.

Since it is automatically loaded, you could do;

@foreach (Product prd in Model.Prod.Where(i=>i.userid==Model.userr.ID))
{
   // ...

   @if(prd.PhotoProducts.FirstOrDefault() != null){
      <div class="img-wrap">
         <img class="img-fluid mehsulimg" src="@prd.PhotoProducts.First().Photo" alt="">
      </div>
   }else{
      <div class="img-wrap">
         <img class="img-fluid mehsulimg" alt="No Photo Available">
      </div>
   }

   // ...
}

Upvotes: 1

Related Questions