防止在自动生成的 GridView 列中进行 HTML 编码 [英] Prevent HTML encoding in auto-generated GridView columns
问题描述
我有一个 GridView 绑定到我构造的 DataTable.表格中的大多数列都包含超链接链接的原始 HTML,我希望该 HTML 在浏览器中呈现为链接,但 GridView 会自动对 HTML 进行编码,因此它呈现为标记.
I have a GridView bound to a DataTable that I construct. Most columns in the table contain the raw HTML for a hypelinklink, and I would like that HTML to render as a link in the browser, but the GridView is automatically encoding the HTML, so it renders as markup.
如何在不显式添加超链接或任何其他列的情况下避免这种情况?
How can I avoid this without explicitly adding HyperLink, or any other, columns?
推荐答案
只需设置 BoundColumn.HtmlEncode
属性为假:
<asp:BoundField DataField="HtmlLink" HtmlEncode="false"/>
恐怕没有简单的方法可以使用 AutoGenerateColumns
= true
.但是,我可以想到两种可能解决您面临的问题的解决方法:
I am afraid that there is no easy way to disable HTML encoding of the contents in a GridView
with AutoGenerateColumns
= true
. However, I can think of two workarounds that might solve the problem you are facing:
选项 1: 继承 GridView
类,覆盖 Render
方法,循环遍历所有单元格,解码它们的内容,然后执行基础方法:
Option 1: Inherit the GridView
class, override the Render
method, loop through all cells, decode their contents, before executing the base method:
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
:
Option 2: In a class inheriting from GridView
or in the Page
or Control
using it, make your own inspection of the DataTable
and create an explicit BoundColumn
for each column:
foreach (DataColumn column in dataTable.Columns)
{
GridViewColumn boundColumn = new BoundColumn
{
DataSource = column.ColumnName,
HeaderText = column.ColumnName,
HtmlEncode = false
};
gridView.Columns.Add(boundColumn);
}
这篇关于防止在自动生成的 GridView 列中进行 HTML 编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!