var query = from c in db.TblKaryawans
join o in db.TblKaryawanKeluargas on c.IDKaryawan equals o.IDKaryawan
select new { c.Nama, o.Hubungan};
ViewBag.karyawan = query;
return View();
view
@foreach (var item in ViewBag.karyawan)
{
<li>@item.Hubungan</li>
}
Error :
'object' does not contain a definition for 'Hubungan'
ViewBag
is dynamic so the view does not have any idea on the type of collection it is enumerating and thus this error. The best way is to create a ViewModel and use that instead of anonymous types
, something like this:-
var query = from c in db.TblKaryawans
join o in db.TblKaryawanKeluargas on c.IDKaryawan equals o.IDKaryawan
select new MyViewModel { Nama = c.Nama, Hubungan = o.Hubungan};
ViewBag.karyawan = query;
Then you can use it like this in your view:-
@foreach (var item in (IEnumerable<MyViewModel>)ViewBag.karyawan)
{
<li>@item.Hubungan</li>
}
Where MyViewModel
will look something like this:-
public class MyViewModel
{
public string Nama { get; set; }
public string Hubungan { get; set; }
}