取得ASP.NET控制項所產生的HTML

這是網友在藍色小鋪發問的內容,版主hunterpo給了一段很棒的範例程式碼,但C#的語法,我實在「沒法Do(台)」,所以就自己動手轉Code一下,貼在這裡留個記錄。

Default.aspx

>form id="form1" runat="server">
  <div>
  <asp:panel id="Panel1" runat="server">
    PANEL 測試內容。
    <asp:button id="Button1" runat="server" text="Button" />
  </asp:panel>
  <div id="div1" runat="server">
    DIV 測試內容。
    <asp:button id="Button2" runat="server" text="Button" />
  </div>
  <asp:literal id="Literal1" runat="server">>/asp:literal>
</form>

Default.aspx.vb


需要先「Imports System.IO」命名;
''' <summary>
    ''' 取得控制項輸出的 HTML
    ''' </summary>
    ''' <param name="control">目標控制項</param>
    Private Function GetHtmlText(ByVal control As Control) As String
        Dim sw As New StringWriter
        Dim hw As New HtmlTextWriter(sw)

        control.RenderControl(hw)
        hw.Flush()

        Return sw.ToString()
    End Function

    Public Overrides Sub VerifyRenderingInServerForm(ByVal control As System.Web.UI.Control)
        '覆寫以取消驗證控制項必須出現在 form 的開頭和結尾標記之間。
        'MyBase.VerifyRenderingInServerForm(control)
    End Sub

    Protected Sub Page_PreInit(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit
        EnableEventValidation = False
    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim p As String = GetHtmlText(Panel1)
        Dim d = GetHtmlText(div1)

        Literal1.Text = "Panel:" & Server.HtmlEncode(p) & "
" & "div:" & Server.HtmlEncode(d)
    End Sub

重點在GetHtmlText方法上,System.IO是我比較少用的類別,順便學習一下。

沒有留言:

張貼留言

感謝您的留言,如果我的文章你喜歡或對你有幫助,按個「讚」或「分享」它,我會很高興的。