我有一个GridView绑定到我构建的DataTable。表格中的大多数列包含超链接的原始HTML,并且我希望该HTML在浏览器中呈现为链接,但GridView会自动编码HTML,因此它会呈现为标记。防止自动生成的GridView列中的HTML编码
如何在不显式添加HyperLink或其他列的情况下避免这种情况?
我有一个GridView绑定到我构建的DataTable。表格中的大多数列包含超链接的原始HTML,并且我希望该HTML在浏览器中呈现为链接,但GridView会自动编码HTML,因此它会呈现为标记。防止自动生成的GridView列中的HTML编码
如何在不显式添加HyperLink或其他列的情况下避免这种情况?
只需将BoundColumn.HtmlEncode
属性设置为false:
<asp:BoundField DataField="HtmlLink" HtmlEncode="false" />
恐怕没有简单的方法来禁用一个GridView
与AutoGenerateColumns
= 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:在一个类从GridView
或Page
或Control
使用它继承,使自己的DataTable
的检查,并为每列一个明确BoundColumn
:
foreach (DataColumn column in dataTable.Columns)
{
GridViewColumn boundColumn = new BoundColumn
{
DataSource = column.ColumnName,
HeaderText = column.ColumnName,
HtmlEncode = false
};
gridView.Columns.Add(boundColumn);
}
那么既然链接的html已经在你的分贝,你可以只输出一个文字控件的HTML。
<asp:TemplateField HeaderText="myLink" SortExpression="myLink">
<ItemTemplate>
<asp:Literal ID="litHyperLink" runat="server" Text='<%# Bind("myLink", "{0}") %>' />
</ItemTemplate>
</asp:TemplateField>
这应该呈现您的链接为原始文本,允许浏览器呈现它作为您期望它的链接。
另一种方法是添加类似下面的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
我能够通过使用约恩休乌 - 罗德提供的解决方案来实现这一点,我修改了一点点使其从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);
}
}
}
使用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;
}
}
}