2009-12-16 134 views
1

我在頁面加載頁面動態添加html代碼。像這樣:
接受動態添加HTML頁面到ASP.NET頁面

protected void Page_Load(object sender, EventArgs e) 
{ 
    //HTML file 
    string file = Server.MapPath("~/ProductsF/DetailFiles/"+Request.QueryString["Page"]);   
    FileInfo fi = new FileInfo(file); 
    HtmlGenericControl hgc = new HtmlGenericControl(); 
    if (File.Exists(file)) 
    { 
     //load html file 
     StreamReader sr = File.OpenText(file); 
     hgc.InnerHtml = sr.ReadToEnd();    
     sr.Close(); 
     sr.Dispose(); 
    } 
    this.ContentPanel.Controls.Add(hgc); 
} 

,但我想訪問預先渲染事件一些HTML控制和改變一些屬性。但我不能訪問這些html控件。

protected override void OnPreRender(EventArgs e) 
{ 
    MakeAllUrlFullyQualified(Page); 
    base.OnPreRender(e); 
} 


private void MakeAllUrlFullyQualified(Control control) 
{ 
    if (control.HasControls()) 
    { 
     foreach (Control child in control.Controls) 
      MakeAllUrlFullyQualified(child); 
    } 

    if (control is HtmlAnchor) 
    { 
     HtmlAnchor anchor = control as HtmlAnchor; 
     anchor.HRef = WebHelper.GetFullyUri(ResolveUrl(anchor.HRef)); 
    } 
    else if (control is HtmlImage) 
    { 
     HtmlImage image = control as HtmlImage; 
     image.Src = WebHelper.GetFullyUri(ResolveUrl(image.Src)); 
    } 
    else if (control is HtmlLink) 
    { 
     HtmlLink link = control as HtmlLink; 
     link.Href = WebHelper.GetFullyUri(ResolveUrl(link.Href)); 
    } 
} 

這段代碼有什麼問題?

回答

1

您正在通過HtmlGenericControl.InnerHTML屬性將HTML添加到您的頁面。你沒有添加控件。

您要添加的唯一控件是HtmlGenericControl(hgc),但您並未添加任何其他控件。

期待通過對User ControlsMaster Pages的文檔,瞭解如何正確地在ASP.NET模板網站

編輯:

要訪問您所添加的HTML,你可以做到以下幾點:

if (control is HtmlGenericControl) 
{ 
    HtmlGenericControl myGenericControl = control as HtmlGenericControl; 
    string innerHtml = myGenericControl.InnerHtml; 
} 

你不能做的是將HTML轉換爲控件。

+0

我想訪問一些在頁面加載時動態添加的html標籤 – mmtemporary 2009-12-16 12:10:48