2013-05-04 39 views
0

我正在嘗試使用MS Visual Studio 2010在ASP.NET中的列表框中顯示的購物車中格式化項目。該程序將每個項目的元素顯示爲串聯字符串,但它的作用是不如我想要的優雅。在ASP.net中嵌入HTML

的cartItem類內我的顯示功能是:

公共功能顯示()作爲字符串 返回Product.ProductName & 「;」 & Product.ProductID & 「(」 + Quantity.ToString()&「在 「& FormatCurrency(Product.UnitPrice)&」 每個)「 端功能

有人告訴我, 」嵌入HTML格式的字符串。添加一個表格,TRS和TDS和CSS「。我在W3School中查找了「嵌入HTML」並沒有看到任何相關內容。我在課堂教科書中找不到這樣的東西。當我嘗試插入像標籤一樣的語句和Visual Studio將它們轉換爲和。我試圖把語句轉換爲響應寫如下:

Response.Write("<html>") 
    Response.Write("<table>") 
    Response.Write("<tr>") 
    Response.Write("<td>") 
    Response.Write("<Product.ProductID>") 
    Response.Write("</td>") 
    Response.Write("<td>") 
    Response.Write("<Product.ProductName>") 
    Response.Write("</td>") 
    Response.Write("</tr>") 
    Response.Write("</table>") 

不過,我在每行說一個錯誤「響應不宣佈它可能無法訪問由於其保護級別。」即使它工作,我也不確定Response.Write適合於格式化打印在列表框中的內容。

我可以嘗試使用另一個控件(細節視圖,窗體視圖)來顯示購物車項目,但我只學會了如何將這些項目綁定到數據庫,並且這些項目位於我的購物車中(cartitemlist類的一個對象,這是一個購物車項目的數組),而不是在數據庫中。

任何幫助將不勝感激。我需要學習這一點,所以我不只是尋找一個複製的解決方案;我想了解如何做到這一點。先謝謝你。 W

回答

1

您可以創建一個用戶控件並實現RenderContents();

public class ProductGrid : System.Web.UI.WebControls.WebControl 
{ 
    public List<Product> DataSource {get; set;} 

    protected override void RenderContents(HtmlTextWriter output) 
    { 
     //here you can iterate through datasource and write the output 
     output.Write("<html><table>"); 

     foreach(row in this.DataSource) 
     { 
      output.Write(String.Format("<td>{0}</td><td>{1}</td></tr>",row.ProductID, row.ProductName)); 
     } 

     output.Write("</table></html>"); 
    } 
} 

現在將此用戶控件放在aspx頁面中,例如可以在div或td中。請記住,如果你是在一個單獨的程序創建該用戶控件是指,在使用「註冊大會」

<div> 
    <ProductGrid Width="100%" ID="ProductGrid1" runat="server" /> 
</div> 

的aspxpage並設置數據源在Page_Load中

ProductGrid1.DataSource = ??? ; //from where you get List<Product>