DataGrid表格上字符串的HTML编码

原因:
在DataGrid的Cell上显示 HTML 编码后的字符串,怎么做呢?如果还有恶意的代码!我想网页就会出乱子啦!

事例:

例如:我有一个DataGrid,用来显数据库中的自定义表的数据,表中含有用户名信息,如果某人在输入了这样的信息
"<script>alert('Hello');</script>" 作为用户名,当浏览含有这个DataGrid的页面时就会弹出一个消息框。我们希望的是
在DataGrid的表格上显示我们输入的信息"<script>alert('Hello');</script>",而不是希望有什么恶意的东西发生。
 
方法:

我的解决办法就是用<asp:TemplateColum>替换所有的<asp:BoundColumn>,下面是具体的办法。

替换前:

将DataGrid表格上字符串的HTML编码进行到底!<asp:BoundColumn DataField="Name" HeaderText="Name"></asp:BoundColumn> 

替换后

将DataGrid表格上字符串的HTML编码进行到底!<asp:TemplateColumn HeaderText="Name">
将DataGrid表格上字符串的HTML编码进行到底!
<ItemTemplate>
   <%
将DataGrid表格上字符串的HTML编码进行到底!
</ItemTemplate>
将DataGrid表格上字符串的HTML编码进行到底!
</asp:TemplateColumn>

 GetCellEntry是进行将字符串转换为 HTML 编码的字符串

将DataGrid表格上字符串的HTML编码进行到底!protected string GetCellEntry( object o )
{
将DataGrid表格上字符串的HTML编码进行到底!
string text = o.ToString();
将DataGrid表格上字符串的HTML编码进行到底!
if ( text != null && text.Trim() != string.Empty )
将DataGrid表格上字符串的HTML编码进行到底!
return Server.HtmlEncode( text );
将DataGrid表格上字符串的HTML编码进行到底!
else
将DataGrid表格上字符串的HTML编码进行到底!
return " ";
将DataGrid表格上字符串的HTML编码进行到底!}

这样的方法让人感到很麻烦,因为我不得不为每一个DataGrid重复一遍这样的工作,于是有了下面的解决方法:

很好的解决方法就是利用OnItemDataBound事件来解决这个问题,可以在datagrid上设置OnItemDataBound

将DataGrid表格上字符串的HTML编码进行到底!<asp:datagrid id="MyDataGrid" runat="server" OnItemDataBound="Item_DataBound"></asp:datagrid>

  代码可以这样写:

将DataGrid表格上字符串的HTML编码进行到底!private void DataGrid1_ItemDataBound( object sender,
将DataGrid表格上字符串的HTML编码进行到底!System.Web.UI.WebControls.DataGridItemEventArgs e )
{
将DataGrid表格上字符串的HTML编码进行到底!
for ( int i = 0; i < DataGrid1.Columns.Count; i++ )
{
将DataGrid表格上字符串的HTML编码进行到底!
if ( DataGrid1.Columns[i].GetType() == typeof(
将DataGrid表格上字符串的HTML编码进行到底!BoundColumn ) 
&&
将DataGrid表格上字符串的HTML编码进行到底!( e.Item.ItemType 
== ListItemType.Item ||
将DataGrid表格上字符串的HTML编码进行到底!e.Item.ItemType 
== ListItemType.AlternatingItem ) )
{
将DataGrid表格上字符串的HTML编码进行到底!BoundColumn boundColumn 
= (BoundColumn)
将DataGrid表格上字符串的HTML编码进行到底!DataGrid1.Columns[i];
将DataGrid表格上字符串的HTML编码进行到底!
string text = DataBinder.Eval( e.Item.DataItem,
将DataGrid表格上字符串的HTML编码进行到底!boundColumn.DataField, boundColumn.DataFormatString );
将DataGrid表格上字符串的HTML编码进行到底!e.Item.Cells[i].Text 
= Server.HtmlEncode( text );
将DataGrid表格上字符串的HTML编码进行到底!}

将DataGrid表格上字符串的HTML编码进行到底!}

将DataGrid表格上字符串的HTML编码进行到底!}
 将DataGrid表格上字符串的HTML编码进行到底!


结论:
datagrid数据表格中的数据将会绑定两次数据源,第一次是在控件自身绑定数据的时候,第二次在触发ItemDataBound
事件的时候,也许这样做没有好的效率.但这也是一种不错的将字符串转换为 HTML 编码的字符串的方法。
希望在ASP.NET的未来版本中含有"HTML-Encode"的选项,用来处理将字符串转换为 HTML 编码的字符串在数据绑定时.

相关文章:

  • 2022-02-05
  • 2022-12-23
  • 2021-09-03
  • 2022-12-23
  • 2022-12-23
  • 2021-09-13
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-22
  • 2021-12-01
  • 2022-12-23
相关资源
相似解决方案