2011-06-22 69 views
1

在MVC3 asp.net這是我的控制器聲明: -怎麼能單獨獲得查詢值

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 /> 
} 

所以輸出: -

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

,但我需要這種類型的答案: -

enter image description here

請問我該怎麼辦? 預先感謝您...

回答

1

創建原材料類

public class RawMaterial 
{ 
    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 RawMaterial { x.Description, y.Quantity }); 

和視圖

<table> 
    <tr> 
     <th>Description</th> 
     <th>Quantity</th> 
    </tr> 

@foreach(var album in ViewBag.rawMaterialRequired) 
{ 
    <tr> 
     <td>@album.Description</td> 
     <td>@album.Quantity</td> 
    </tr> 
} 

</table> 
+0

謝謝主席先生的。 ..你的回答是適當的。先生,當我運行我的程序時出現錯誤,「'對象'不包含'描述'的定義,'對象'不包含'數量'的定義,我應該怎麼做?我應該採取除ViewBag以外的其他事情嗎? –

+0

@Pushpendra,已更新。 –

+0

是的,您建議我創建公開課RawMaterial { public string Description {get;組; } public int Quantity {get;組; } }現在怎樣才能將這個查詢的結果帶入這個類的對象中。 –