如何打印表的两列的值

时间:2011-06-29 06:24:18

标签: asp.net-mvc asp.net-mvc-2 asp.net-mvc-3 razor

我正在研究MVC3 asp.net。 这是我在控制器中的sr = tatement: -

ViewBag.rawMaterialRequired = (from x in db.RawMaterial 
 join y in db.ProductFormulation on x.ID equals y.RawMaterialID 
 where y.ProductID == p select new { x.Description, y.Quantity });

这是我在View中的代码: -

 @foreach(var album in ViewBag.rawMaterialRequired)
         {
                @album<br />
         }
         </div>

这是我的输出: -

{ Description = Polymer 26500, Quantity = 10 }
{ Description = Polymer LD-M50, Quantity = 10 }
{ Description = Titanium R-104, Quantity = 20 }

这是我想要的输出: -

enter image description here

1 个答案:

答案 0 :(得分:5)

首先设计一个视图模型:

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>