0

I have my code written as follows

 var RecentTransactions = db.Leave_Data.OrderByDescending(l => l.Applied_Date).Take(5).Select(x => new
 {
      StartDate = x.Start_Date,
      LeavePurpose = x.Leave_Purpose,
      LeaveType = x.Leave_Type.Leave_Type1,
      LeaveStatus = x.Leave_Status.Status_Name
   });

 ViewBag.RecentTransactions = RecentTransactions.ToList();

This is how I written in my view

@foreach (var item in ViewBag.RecentTransactions)
{
     <li class="list-group-item">                         
     <span class="pull-right">@item.LeaveStatus</span>
     </li>
}

Additional information: 'object' does not contain a definition for 'LeaveStatus'

So can some one help me

Updated code if any better way let me know

List<Leave_Data> ld = new List<Leave_Data>();
Leave_Data l = new Leave_Data();

var RecentTransactions = db.Leave_Data.OrderByDescending(i => i.Applied_Date).Take(5).Select(x => new
{
   StartDate = x.Start_Date,
   LeavePurpose = x.Leave_Purpose,
   LeaveType = x.Leave_Type.Leave_Type1,
   LeaveStatus = x.Leave_Status.Status_Name
 });

 foreach(var result in RecentTransactions)
 {
   l.Start_Date = result.StartDate;
   l.Leave_Purpose = result.LeavePurpose;
   l.Leave_Type = new Leave_Type();
   l.Leave_Type.Leave_Type1 = result.LeaveType;
   l.Leave_Status = new Leave_Status();
   l.Leave_Status.Status_Name = result.LeaveStatus;
   ld.Add(l);
  }
 ViewBag.RecentTransactions = ld;
Developer
  • 8,390
  • 41
  • 129
  • 238
  • What is the error? – Divyang Desai Oct 10 '16 at 11:16
  • `Additional information: 'object' does not contain a definition for 'LeaveStatus` – Developer Oct 10 '16 at 11:17
  • Yes I am getting the data – Developer Oct 10 '16 at 11:21
  • 2
    You passing an anonymous object. You need to create a view model containing the properties you need and map your query to a collection of the view model - ..Select(x => new MyModel { StartDate = x.Start_Date, .... }` –  Oct 10 '16 at 11:21
  • @Dotnet Refer [this](http://stackoverflow.com/questions/21962442/viewbag-runtimebinderexception-object-does-not-contain-a-definition) – Divyang Desai Oct 10 '16 at 11:24
  • 1
    Refer also [this article](http://gregshackles.com/anonymous-view-models-in-asp-net-mvc-using-dynamics/) for more detailed explanation –  Oct 10 '16 at 11:31
  • You can do it all in a `.Select(x => new Leave_Data { Start_Date = x.StartDate, Leave_Purpose = x.Leave_Purpose, LeaveType = new LeaveType { Leave_Type1 = x.LeaveType }, ..... });` But why does you model need to contain complex objects? And why are you using `ViewBag` instead of passing the model to the view? –  Oct 10 '16 at 12:28

0 Answers0