Cezar Cezar - 2 months ago 7x
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)

It shows 3 times same data.


You can get the first warehouse only from your model:

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


Then you can loop to show the keys:

@foreach (var x in Model)