2011-06-29 51 views
0

我正在使用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 }); 

这是我在视图的代码: -

@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

回答

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> 
+0

先生,非常感谢您的帮助,我真的不能表达我对您的帮助的高兴。上帝在你的生命中给予你所有的快乐......真的,先生,你为我做了非常有价值的工作。再次感谢... –