開始通過設計視圖模型:
public class ProductLineViewModel
{
public string Description { get; set; }
public int Quantity { get; set; }
}
然後在你的控制器使用這個視圖模型:
ViewBag.rawMaterialRequired =
from x in db.RawMaterial
join y in db.ProductFormulation on x.ID equals y.RawMaterialID
where y.ProductID == p
select new ProductLineViewModel
{
Description = x.Description,
Quantity = y.Quantity
};
和視圖裏面:
<table>
<thead>
<tr>
<th>Description</th>
<th>Quantity</th>
</tr>
</thead>
<tbody>
@foreach(var product in (IEnumerable<ProductLineViewModel>)ViewBag.rawMaterialRequired)
{
<tr>
<td>@product.Description</td>
<td>@product.Quantity</td>
</tr>
}
</tbody>
</table>
這是第一次踏進改善你的代碼。第二步由除暴安良ViewBag
和使用強類型的意見,並顯示模板:
public ActionResult Foo()
{
var model =
from x in db.RawMaterial
join y in db.ProductFormulation on x.ID equals y.RawMaterialID
where y.ProductID == p
select new ProductLineViewModel
{
Description = x.Description,
Quantity = y.Quantity
};
return View(model);
}
,並在視圖中刪除任何醜陋環路感謝顯示模板:
@model IEnumerable<ProductLineViewModel>
<table>
<thead>
<tr>
<th>Description</th>
<th>Quantity</th>
</tr>
</thead>
<tbody>
@Html.DisplayForModel()
</tbody>
</table>
和顯示模板中(~/Views/Shared/DisplayTemplates/ProductLineViewModel.cshtml
):
@model ProductLineViewModel
<tr>
<td>@Html.DisplayFor(x => x.Description)</td>
<td>@Html.DisplayFor(x => x.Quantity)</td>
</tr>
先生,非常感謝您的幫助,我真的不能表達我對您的幫助的高興。上帝在你的生命中給予你所有的快樂......真的,先生,你爲我做了非常有價值的工作。再次感謝... –