2014-02-12 23 views
0

我正在用asp.net創建一個站點。我希望能夠在輸出發送給用戶之前編輯我的主頁面,頁面和用戶控件的html輸出。我在互聯網上發現了一些應該允許我通過預渲染函數編輯代碼的功能,但是它們都不起作用。在發送給用戶之前編輯輸出html

我想從我的代碼中移除html註釋,例如。渲染之前可以在html上執行一些正則表達式函數嗎?

+0

您應該在部署過程中一次性完成,而不是Web服務器的任務。 – Maxim

回答

1

如果您只是想在代碼中呈現給客戶端之前刪除代碼中的評論,請改變評論的方式。使用服務器端註釋= <%-- hi --%>

所以這樣的:

<!-- Don't remove the <p> below because our stupid clients are too stupid to figure out this form without it --> 
<p>Tip: The field labeled "First Name" is meant for your first name. Don't type in your last name in this box.</p> 
<%-- Don't remove this <p> either because both our clients and our boss are too dumb to figure it out --%> 
<p>Tip 2: Type your last name in the field labeled "Last Name".</p> 

將呈現爲:

<!-- Don't remove the <p> below because our stupid clients are too stupid to figure out this form without it --> 
<p>Tip: The field labeled "First Name" is meant for your first name. Don't type in your last name in this box.</p> 

<p>Tip 2: Type your last name in the field labeled "Last Name".</p> 


但是,如果你確實需要渲染的前編輯HTML輸出客戶端在全球範圍內,並且您不能在代碼中修復它,您可以在主頁面中執行此操作:

protected override void Render(System.Web.UI.HtmlTextWriter writer) 
{ 
    StringWriter sw = new StringWriter(); 
    HtmlTextWriter tw = new HtmlTextWriter(sw); 
    base.Render(tw); 
    string yourHTML = sw.ToString(); 
    // do stuff with yourHTML 
    writer.Write(yourHTML); 
    tw.Dispose(); 
    sw.Dispose(); 
} 

所以在很簡單例如,如果你的代碼

<h1>I'm a big fat h1</h1> 

,你可以在該函數有:

yourHTML = yourHTML.Replace("<h1>","<h5>"); 
yourHTML = yourHTML.Replace("</h1>", "</h5>"); 

所以,現在,上面的代碼被渲染爲

<h5>I'm a big fat h1</h5> 

要完成將所有h1標籤更改爲01的非常合法的要求它們被呈現給瀏覽器之前,它們是。

+0

我收到了一條異常,表示正在嘗試寫入封閉流。 – Jerodev

+0

@Jerodev。嗯。我以前沒遇到過這個問題。我更新了答案。看看是否有幫助。改變了最後幾行。 – MikeSmithDev

+0

它仍然給出相同的錯誤。 – Jerodev

0

我想你要找的是什麼ControlAdapters

我以前用它們與SharePoint所有我,使輸出的代碼更容易。你在WebConfig中註冊它們,然後渲染的控件通過。此時,您可以使用正則表達式來處理和修改已標記的標記

相關問題