0
I have a table of real estate and real estate photos, with the respective models:
Real estate
[Key]
public int ImovelId { get; set; }
public int? CategoriaId { get; set; }
public string Endereco { get; set; }
public string Numero { get; set; }
Immoveable
[Key]
public int Id { get; set; }
public int ImovelId { get; set; }
public string Foto { get; set; }
In Controller I have this code:
IList<Imoveis> imoveisLista = new List<Imoveis>();
var imoveis = _context.Imoveis
.Where(i => i.LocacaoVenda == "L")
.Where(i => i.Bairro == bairro)
.Where(i => i.VisivelAluguel == 1)
.ToList();
foreach (var item in imoveis)
{
imoveisLista.Add(item);
var foto = _context.ImoveisFotos
.Where(x => x.ImovelId == item.ImovelId)
.Select(x => x.Foto).Count();
if (foto == 0)
{
ViewBag.Foto = "img_padrao.jpg";
}
else if(foto >= 1)
{
ViewBag.Foto = _context.ImoveisFotos
.Where(x => x.ImovelId == item.ImovelId)
.Select(x => x.Foto).First();
}
}
ViewData["ListaImoveis"] = imoveisLista;
And in View
@foreach (var item in ViewData["ListaImoveis"] as IList<Imoveis>)
{
<div class="row">
<div class="col-md-12">
<div class="card p-1 mb-2 bg-light">
<h5 class="card-header text-left text-dark font-weight-bold">
<i class="fas fa-map-marker text-dark"></i>
<span>@item.Bairro</span>
-
<span>@item.Endereco</span>,
<span>@item.Numero</span>
-
<span>@item.Complemento</span>
</h5>
<div class="card-body">
<div class="row">
<div class="col-md-5 text-center">
<a href="detalhes?id=57">
<img class="img-fluid cover" src="https://230.112.09.34/content/uploads/imoveis/fotos/@ViewBag.Foto" />
The list of properties comes straight, but the whole list repeats the same photo, instead of its primary table. My goal was to take the first photo of each property and display. Below how it looks:
How to solve this?
@Mjslasher, vlw even. The key to everything was to use Viewmodel. Then in the foreach as you said, I used a Count to go through the Qtde of photos, if it returned null, specified a private string as the default photo, if it had, picked the first of the list with First(), and finally played in the property Viewmodel Photo.
– Claudinei Ferreira