2017-03-07 126 views
1

我在控制器在視圖中顯示兩個模型?

public ActionResult Search(int? id) 
{ 
    var yearSummary = from ti in db.TrainingRecordDBSet 
         join si in db.StaffInfoDBSet 
          on ti.StaffId equals si.StaffId 
         group ti by ti.Year into g 
         select new { 
          Year = g.Key, 
          SHour = g.Sum(ti => ti.Hour) 
         }; 

    var trainingQ = from t in db.TrainingRecordDBSet.Include("StaffInfo") 
        where t.StaffId == id orderby t.StaffId, t.Tid 
        select t; 

    var list = trainingQ.ToList(); 

    ViewBag.yearSummary = yearSummary; 

    return View(list); 
} 

我想從數據庫和「yearSummary」在數據庫中,其中的「traingingQ」已經成功同時顯示「traingingQ」兩分型,但「yearSummary」我不知道如何在視圖中展示,親愛的朋友可以告訴我怎麼做?

這裏是視圖的編碼,並且不工作

@var yearSummary = (dynamic) ViewBag.yearSummary; 
@foreach (var item in Model) 
{ 
    <tr> 
     <td> 
      @*var yearSummary = (StaffInfoEditViewModel) ViewBag.yearSummary;*@ 
      @{ 
       Html.DisplayFor(modelItem => item.Shour); 
      } 
     </td> 
     <td> 
      @{ 
       Html.DisplayFor(modelItem => item.Shour); 
      } 
     </td> 
    </tr> 
} 
</table> 

非常感謝你!

+0

你能告訴什麼呢變種yearSummary回報? – Usman

回答

4

使一個類(模型)來持有的觀點需要的數據..

public class SearchVM 
{ 
    public IEnumerable<YearSummary> YearSummary { get; set; } 
    public IEnumerable<TrainingQ> Training { get; set; } 
} 

public ActionResult Search(int? id) 
{ 
    var model = new SearchVM 
    { 
     YearSummary = (from ti in db.TrainingRecordDBSet 
         join si in db.StaffInfoDBSet 
          on ti.StaffId equals si.StaffId 
         group ti by ti.Year into g 
         select new { 
          Year = g.Key, 
          SHour = g.Sum(ti => ti.Hour) 
         }) 
     .AsEnumerable() 
     .Select(ys => new YearSummary { Year = ys.YEar, SHour = ys.Shour {) 
     .ToList(), 

     TrainingQ = (from t in db.TrainingRecordDBSet.Include("StaffInfo") 
        where t.StaffId == id orderby t.StaffId, t.Tid 
        select t) 
     .ToList() 
    }; 

    return View(model); 
} 
+0

非常感謝!你真好!! ^^ !! –

+0

^^ !!我可否知道如何在視圖中使用數據? –

相關問題