將DataGrid表格上字串的HTML編碼進行到底!

來源:互聯網
上載者:User

                          DataGrid表格上字串的HTML編碼



原因:

在DataGrid的Cell上顯示 HTML 編碼後的字串,怎麼做呢?如果還有惡意的代碼!我想網頁就會出亂子啦!

案例:

例如:我有一個DataGrid,用來顯資料庫中的自訂表格的資料,表中含有使用者名稱資訊,如果某人在輸入了這樣的資訊

"<script>alert('Hello');</script>" 作為使用者名稱,當瀏覽含有這個DataGrid的頁面時就會彈出一個訊息框。我們希望的是

在DataGrid的表格上顯示我們輸入的資訊"<script>alert('Hello');</script>",而不是希望有什麼惡意的東西發生。

 

方法:

我的解決辦法就是用<asp:TemplateColum>替換所有的<asp:BoundColumn>,下面是具體的辦法。

替換前:

<asp:BoundColumn DataField="Name" HeaderText="Name"></asp:BoundColumn> 

替換後

<asp:TemplateColumn HeaderText="Name">

<ItemTemplate>

   <%# GetCellEntry( DataBinder.Eval(Container, "DataItem.Name" ) ) %>

</ItemTemplate>

</asp:TemplateColumn>

 GetCellEntry是進行將字串轉換為 HTML 編碼的字串

protected string GetCellEntry( object o )

{

string text = o.ToString();

if ( text != null && text.Trim() != string.Empty )

return Server.HtmlEncode( text );

else

return " ";

}

這樣的方法讓人感到很麻煩,因為我不得不為每一個DataGrid重複一遍這樣的工作,於是有了下面的解決方案:

很好的解決方案就是利用OnItemDataBound事件來解決這個問題,可以在datagrid上設定OnItemDataBound

<asp:datagrid id="MyDataGrid" runat="server" OnItemDataBound="Item_DataBound"></asp:datagrid>

  代碼可以這樣寫:

private void DataGrid1_ItemDataBound( object sender,

System.Web.UI.WebControls.DataGridItemEventArgs e )

{

for ( int i = 0; i < DataGrid1.Columns.Count; i++ )

{

if ( DataGrid1.Columns[i].GetType() == typeof(

BoundColumn ) &&

( e.Item.ItemType == ListItemType.Item ||

e.Item.ItemType == ListItemType.AlternatingItem ) )

{

BoundColumn boundColumn = (BoundColumn)

DataGrid1.Columns[i];

string text = DataBinder.Eval( e.Item.DataItem,

boundColumn.DataField, boundColumn.DataFormatString );

e.Item.Cells[i].Text = Server.HtmlEncode( text );

}

}


結論:

datagrid資料表格中的資料將會綁定兩次資料來源,第一次是在控制項自身綁定資料的時候,第二次在觸發ItemDataBound

事件的時候,也許這樣做沒有好的效率.但這也是一種不錯的將字串轉換為 HTML 編碼的字串的方法。

希望在ASP.NET的未來版本中含有"HTML-Encode"的選項,用來處理將字串轉換為 HTML 編碼的字串在資料繫結時.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.