在视图中显示两个模型?

时间:2017-03-07 01:45:49

标签: c# asp.net-mvc razor

我在Controller中有两个模型

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);
}

我想在数据库中显示“traingingQ”和数据库中的“yearSummary”,其中“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>

非常感谢!!

1 个答案:

答案 0 :(得分: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);
}