HTML encoding of strings in the DataGrid table
Cause:
How can I display HTML encoded strings on the cell of the DataGrid? If there are other maliciousCode! I think the web page will be messy!
Example:
For example, I Have A DataGrid used to display the data of a custom table in the database. The table contains username information.
"<SCRIPT> alert ('hello'); </SCRIPT>" as the user name, a message box is displayed when you browse the page containing this DataGrid. What we want is
Show the input information "<SCRIPT> alert ('hello'); </SCRIPT>" in the DataGrid table, instead of expecting something malicious.
Method:
My solution is to replace all <asp: boundcolumn> with <asp: templatecolum>. The following is a specific solution.
Before replacement:
< ASP: boundcolumn Datafield = "Name" Headertext = "Name" > </ ASP: boundcolumn >
After replacement
< ASP: templatecolumn Headertext = "Name" >
< Itemtemplate >
<% # Getcellentry (databinder.Eval(Container,"Dataitem. Name")) %>
</ Itemtemplate >
</ ASP: templatecolumn >
Getcellentry is an HTML-encoded string.
Protected String Getcellentry ( Object O)
{
String Text = O. tostring ();
If (Text ! = Null && Text. Trim () ! = String . Empty)
Return Server. htmlencode (text );
Else
Return " " ;
}
This method is very troublesome, because I have to repeat this job for each DataGrid, so I have the following solution:
A good solution is to use the onitemdatabound event to solve this problem. You can set onitemdatabound on the DataGrid.
< ASP: DataGrid ID = "Mydatagrid" Runat = "Server" Onitemdatabound = "Item_databound" > </ ASP: DataGrid >
The code can be written as follows:
Private Void Datagrid1_itemdatabound ( Object Sender,
System. Web. UI. webcontrols. datagriditemeventargs E)
{
For ( Int I = 0 ; I < Datagrid1.columns. Count; I ++ )
{
If (Maid [I]. GetType () = Typeof (
Boundcolumn) &&
(E. Item. itemtype = Listitemtype. Item |
E. Item. itemtype = Listitemtype. alternatingitem ))
{
Boundcolumn=(Boundcolumn)
Datagrid1.columns [I];
StringText=Databinder. eval (E. Item. dataitem,
Boundcolumn. datafield, boundcolumn. dataformatstring );
E. Item. cells [I]. Text=Server. htmlencode (text );
}
}
}
conclusion:
data in the DataGrid data table is bound to the data source twice, the first time when the control binds data, the second time when the itemdatabound
event is triggered, this may not be efficient. but this is also a good way to convert a string to an HTML-encoded string.
you want.. Net in future versions, it contains the "HTML-encode" option, which is used to process the string converted to HTML encoding during data binding.