2010-01-30 110 views
13

我有一個GridView綁定到我構建的DataTable。表格中的大多數列包含超鏈接的原始HTML,並且我希望該HTML在瀏覽器中呈現爲鏈接,但GridView會自動編碼HTML,因此它會呈現爲標記。防止自動生成的GridView列中的HTML編碼

如何在不顯式添加HyperLink或其他列的情況下避免這種情況?

回答

22

只需將BoundColumn.HtmlEncode屬性設置爲false:

<asp:BoundField DataField="HtmlLink" HtmlEncode="false" />


恐怕沒有簡單的方法來禁用一個GridViewAutoGenerateColumns= true內容HTML編碼。不過,我可以認爲這可能解決你所面臨的問題,有兩種解決方法:

選項1:繼承了GridView類,覆蓋Render方法,遍歷所有細胞中,解碼的內容,執行基本方法之前:

for (int i = 0; i < Rows.Count; i++) 
{ 
    for (int j = 0; j < Rows[i].Cells.Count; j++) 
    { 
     string encoded = Rows[i].Cells[j].Text; 
     Rows[i].Cells[j].Text = Context.Server.HtmlDecode(encoded); 
    } 
} 

選項2:在一個類從GridViewPageControl使用它繼承,使自己的DataTable的檢查,併爲每列一個明確BoundColumn

foreach (DataColumn column in dataTable.Columns) 
{ 
    GridViewColumn boundColumn = new BoundColumn 
     { 
      DataSource = column.ColumnName, 
      HeaderText = column.ColumnName, 
      HtmlEncode = false 
     }; 
    gridView.Columns.Add(boundColumn); 
} 
1

那麼既然鏈接的html已經在你的分貝,你可以只輸出一個文字控件的HTML。

<asp:TemplateField HeaderText="myLink" SortExpression="myLink"> 
    <ItemTemplate> 
     <asp:Literal ID="litHyperLink" runat="server" Text='<%# Bind("myLink", "{0}") %>' /> 
    </ItemTemplate> 
</asp:TemplateField> 

這應該呈現您的鏈接爲原始文本,允許瀏覽器呈現它作爲您期望它的鏈接。

7

另一種方法是添加類似下面的RowDataBound事件處理程序...

If e.Row.RowType = DataControlRowType.Header Then 
     For Each col As TableCell In e.Row.Cells 
      Dim encoded As String = col.Text 
      col.Text = Context.Server.HtmlDecode(encoded) 
     Next 
    End If 
7

我能夠通過使用約恩休烏 - 羅德提供的解決方案來實現這一點,我修改了一點點使其從GridView的RowDataBound事件中工作。

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) 
{ 
    if (e.Row.RowType == DataControlRowType.DataRow) 
    { 
      for (int j = 0; j < e.Row.Cells.Count; j++) 
      { 
       string encoded = e.Row.Cells[j].Text; 
       e.Row.Cells[j].Text = Context.Server.HtmlDecode(encoded); 
      } 

    } 
} 
1

使用OnRowCreated

protected void gvFm_RowCreated(object sender, GridViewRowEventArgs e) 
    { 
     foreach (TableCell cell in e.Row.Cells) 
     { 
      BoundField fldRef = (BoundField)((DataControlFieldCell)cell).ContainingField; 
      switch (fldRef.DataField) 
      { 
       case "ColToHide": 
        fldRef.Visible = false;       
        break; 
       case "ColWithoutEncode": 
        fldRef.HtmlEncode = false;       
        break; 
      } 
     } 
    }