2011-06-29 110 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

先生,非常感謝您的幫助,我真的不能表達我對您的幫助的高興。上帝在你的生命中給予你所有的快樂......真的,先生,你爲我做了非常有價值的工作。再次感謝... –