Cezar Cezar - 3 months ago 18
C# Question

Passing my ViewModel to View and getting single data

My ViewModel looks that:

public class WerehouseViewModel
{
public Werehouse Werehouse { get; set; }
public WerehouseKey WerehouseKey { get; set; }
}


That's how I get data from database

var viewModel =
from Wh in db.Werehouses
join WhK in db.WerehouseKeys on Wh.WhID equals WhK.WhID
where Wh.WhID == id
select new WerehouseViewModel { Werehouse = Wh, WerehouseKey = WhK };
return View(viewModel);


I know I have to use IEnumerable type to show in my View, but I would like to show only one Werehouse (and only one is in view model) and Keys (let's say that there are three keys for one werehouse). How can I show one Werehouse in list and below all keys in table? Because when I use

@foreach (var x in Model)
{
<div>@x.Werehouse.Kod_magazynu</div>
<div>@x.Werehouse.Ulica</div>
<div>@x.Werehouse.Numer_magazynu</div>
<div>@x.Werehouse.Miasto</div>
}


It shows 3 times same data.

Answer

You can get the first warehouse only from your model:

@{
   var warehouse = Model.Select(x=> x.Werehouse).FirstOrDefault();

   <div>@warehouse.Kod_magazynu</div>
   <div>@warehouse.Ulica</div>
   <div>@warehouse.Numer_magazynu</div>
   <div>@warehouse.Miasto</div>
}

Then you can loop to show the keys:

@foreach (var x in Model)
{
    <div>@x.WerehouseKey.SomeProperty</div>
}
Comments