如何在GridView单元格中的(即 )中呈现已解码的HTML
我正在将GridView绑定到LINQ查询。 LINQ语句创建的对象中的某些字段是字符串,需要包含新行。
显然,GridView对每个单元格中的所有内容进行HTML编码,因此我无法在单元格中插入
来创建新行。
如何告诉GridView不要HTML编码单元格的内容?
也许我应该使用不同的控件呢?
你能订阅RowDataBound事件吗? 如果可以,你可以运行:
if (e.Row.RowType == DataControlRowType.DataRow) { string decodedText = HttpUtility.HtmlDecode(e.Row.Cells[0].Text); e.Row.Cells[0].Text = decodedText; }
将HtmlEncode
属性设置为false
怎么样? 对我来说,这更简单。
输出中是否保留了正常的换行符? 如果是这样,您可以发送换行符,并使用css样式white-space: pre
,这将保留换行符,空格和制表符。
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { for (int i = 0; i < e.Row.Cells.Count; i++) { if (e.Row.RowType == DataControlRowType.DataRow) { string decodedText = HttpUtility.HtmlDecode(e.Row.Cells[i].Text); e.Row.Cells[i].Text = decodedText; } } }
Booysen的回答只适用于一栏。 如果在RowDataBound事件中运行循环,则可以将变量替换为[0],并根据需要对每列执行此操作。 这是我做的:
protected void gridCart_RowDataBound(object sender, GridViewRowEventArgs e) { for (int i = 1; i < 4; i++) { if (e.Row.RowType == DataControlRowType.DataRow) { string decode = HttpUtility.HtmlDecode(e.Row.Cells[i].Text); e.Row.Cells[i].Text = decode; } } }
由于我的数据,我故意在1开始,但很明显它将适用于你需要的任何东西。
我通过首先使用多线文本框将数据插入到我的sql-server表中来解决这个问题
replace (txt = Replace(txt, vbCrLf,"
"))
然后我使用Ray Booysen的解决方案将其返回到gridview:
Protected Sub grdHist_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles grdHist.RowDataBound Dim col1 As String = HttpUtility.HtmlDecode(e.Row.Cells(2).Text) e.Row.Cells(2).Text = col1 End Sub
protected void gvHead_OnRowDataBound(object sender, GridViewRowEventArgs e) { for (int i = 0; i < e.Row.Cells.Count; i++) e.Row.Cells[i].Text = HttpUtility.HtmlDecode(e.Row.Cells[i].Text); }
您必须绑定到DataBoundGrid事件并更改要呈现HTML代码的列的Rendering。
public event EventHandler DataBoundGrid { add { ctlOverviewGridView.DataBound += value; } remove { ctlOverviewGridView.DataBound -= value; } } ctlOverview.DataBoundGrid += (sender, args) => { ((sender as ASPxGridView).Columns["YourColumnName"] as GridViewDataTextColumn).PropertiesTextEdit.EncodeHtml = false; };
@Ray Booysen
答案是正确的,但在某些情况下HtmlDecode()无法解决您的问题。 你可以使用UrlDecode()而不是HtmlDecode()。
这是另一个解决方案:
if (e.Row.RowType == DataControlRowType.DataRow) { string decodedText = HttpUtility.UrlDecode(e.Row.Cells[0].Text); e.Row.Cells[0].Text = decodedText; }