如何在编辑视图MVC中显示其他只读视图数据

时间:2012-01-20 06:22:48

标签: asp.net-mvc-3 viewbag

我有一个View来处理编辑操作,用于编辑每周更新的体重和营养。编辑单一模型都很好。我正在使用EditorFor来创建字段。

我的问题是我还要显示上周结果的只读版本作为指南,但我想使用DisplayFor,以便将bools格式化为禁用复选框,并根据模型中的格式设置日期格式。我将模型添加到Viewbag并试图通过使用@ Html.DisplayFor(x => x.BodyWeight,(myproject.Models.WeeklyReport)ViewBag.LastReport)访问它,但它只是调出模型中的数据发送到视图而不是Viewbag数据。在保持模型的约束/格式完整的同时显示此类数据的最佳方法是什么?

感谢。

查看

@model myproject.Models.WeeklyReport

<h2>Weekly Report - Week 1</h2>
@using (Html.BeginForm())
{
    @Html.ValidationSummary(true)

    <table class="weeklyreport">
        <tr>
            <th>Week</th>
            <td class="result-bold">Goals</td>
            <td>Current Week</td>
        </tr>
        <tr>
            <th>Body Weight</th>
            <td class="result-bold">@Html.DisplayFor(x => x.BodyWeight, (myproject.Models.WeeklyReport)ViewBag.Goals)</td>
            <td>@Html.EditorFor(model => model.BodyWeight)
                @Html.ValidationMessageFor(model => model.BodyWeight)</td>
        </tr>
        <tr>
            <th>Diary Reviewed</th>
            <td class="result-bold">@Html.DisplayFor(x => x.DiaryReviewed, (myproject.Models.WeeklyReport)ViewBag.Goals)</td>
            <td>@Html.EditorFor(model => model.DiaryReviewed)
                @Html.ValidationMessageFor(model => model.DiaryReviewed)</td>
        </tr>
    </table>

控制器

public ActionResult Edit(int id)
{
    WeeklyReport goal = new WeeklyReport()
    {  
        BodyWeight = 60,
        DiaryReviewed = true
    };

    WeeklyReport rpt = new WeeklyReport()
    {
        BodyWeight = 68,
        DiaryReviewed = false

    };
    ViewBag.LastReport = goal;
    return View(rpt);
}

1 个答案:

答案 0 :(得分:0)

您可以创建一个viewmodels或partialViews,并将viewbag项目传递给partial。

viewmodel用法的一个例子

 public class WeeklyReportViewModel
    {
      public WeeklyReport LastReport { get; set; }
      public WeeklyReport Report { get; set; }
    }

合并报告

public ActionResult Edit(int id)
{
  WeeklyReport goal = new WeeklyReport()
  {  
    BodyWeight = 60,
    DiaryReviewed = true
  };

  WeeklyReport rpt = new WeeklyReport()
  {
    BodyWeight = 68,
    DiaryReviewed = false

  };

  WeeklyReportViewModel viewmodel = new WeeklyReportViewModel()
  {
    LastReport = goal,
    ActualReport = rpt
  }

  return View(viewmodel);

}

在视图中

@model myproject.ViewModels.WeeklyReportViewModel 

@Html.DisplayFor(x => x.LastReport.BodyWeight)