2012-04-22 133 views
1

我正在使用HtmlTextWriter爲我創建一些HTML。我想測試我的頁面是否可以正常工作,但它不能渲染div。HtmlTextWriter不會呈現

using System; using System.Collections.Generic; using System.Web; using System.Web.UI; using System.Web.UI.WebControls;使用System.IO的 ;

public partial class web_content_notes_Default : System.Web.UI.Page 
{ 
    protected void Page_Load(object sender, EventArgs e) 
    { 
     /* Configuration Start */ 
     string thumb_directory = "img/thumbs"; 
     string orig_directory = "img/original"; 
     int stage_width = 600; 
     int stage_height = 480; 
     Random random = new Random(); 

     // array of allowed file type extensions 
     string[] allowed_types = { "bmp", "gif", "png", "jpg", "jpeg", "doc", "xls" }; 

     /* Opening the thumbnail directory and looping through all the thumbs: */ 
     foreach (string file in Directory.GetFiles(thumb_directory)) 
     { 
      string title = Path.GetFileNameWithoutExtension(file); 
      if (allowed_types.Equals(Path.GetExtension(file)) == true) 
      { 
       int left = random.Next(0, stage_width); 
       int top = random.Next(0, 400); 
       int rotation = random.Next(-40, -40); 

       if ((top > stage_height - 130) && (left > stage_width - 230)) 
       { 
        top -= 120 + 130; 
        left -= 230; 
       } 


      } 

      //display the files in the directory in a label for testing 
      Label1.Text = (file); 

      StringWriter stringWriter = new StringWriter(); 

      // Put HtmlTextWriter in using block because it needs to call Dispose. 
      using (HtmlTextWriter writer = new HtmlTextWriter(stringWriter)) 

       // The important part: 
       writer.Write("<div>testing123</div>"); 

     } 

    } 
} 

我想將各種變量添加到div中。

我該怎麼做?我記得在傳統的ASP/VBScript中你不得不換行代碼<% code %>不知道這是ASP.NET/C#的情況下

回答

2

我想測試,如果我的頁面的實際工作,但它不呈現DIV。

不,不會。看看你在做什麼:

StringWriter stringWriter = new StringWriter(); 
using (HtmlTextWriter writer = new HtmlTextWriter(stringWriter)) 
    writer.Write("<div>testing123</div>"); 

所以,你寫信給StringWriter。你正在做沒有與該字符串作家:文本是在內存中,你讓它得到垃圾回收,基本上。

如果您想寫入Page的回覆,您必須將結果寫入Page.Response。但是您應該決定是否要控制請求的響應的整個 - 在這種情況下Page可能不是非常合適 - 或者只是一個控件,在這種情況下,您應該將代碼置於自定義控制

+0

噢好吧,所以我有不需要的代碼? – 2012-04-22 12:03:58

+0

@ sp-1986:那麼你的代碼不是*有用*。看我的編輯。 – 2012-04-22 12:05:03

+0

喬恩我看你是一位作家。我也看到你的書有5 *條評論。 – 2012-04-22 12:05:31