2012-01-20 99 views
0

我有一個處理編輯操作的視圖,用於編輯體重和營養的每週更新。編輯單一模型是很好的。我正在使用EditorFor創建字段。如何在編輯視圖中顯示其他只讀視圖數據MVC

我的問題是,我還想顯示上週結果的只讀版本作爲指南,但我想使用DisplayFor,以便它格式化布爾被禁用複選框並格式化日期基於我的格式模型。我將該模型添加到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); 
} 

回答

0

您可以創建的ViewModels或partialViews和viewbag項目傳遞給部分。

視圖模型用法的例子

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) 
相關問題