从设计一个视图模型开始:
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>