开发者

GridView and Html Encoding

I've recently upgraded a client's web site to .NET 4 and we've found out during the process that now GridView column开发者_Go百科 values are automatically HTML encoded.

They have wide use of HTML strings in their code so we must turn that off. I know one solution would go over each column and add HtmlEncode="false". My question is - is there a way to set this to be the default for all GridView columns in this application?

Thanks!


I found this solution to solve this problem.

 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
               for (int i = 0; i < e.Row.Cells.Count; i++) 
               {
                   string encoded = e.Row.Cells[i].Text;
                   e.Row.Cells[i].Text = Context.Server.HtmlDecode(encoded);
               }
        }
    }


I don't think there is any way to do it by default as this was put in as a safety measure by default so that developers would need to consider turning it off.

To get around it you would need to turn it off column by column or you could inherit a new control from GridView and make it set each column be default to false. You could then just do a search and replace for GridView with your new control. I wouldn't recommend this method though.

Best would be to interrogate each column in the application and turn it off. It's safer and it makes you actually consider where you want to open the door for the possibility of HTML / javascript injection. Better safe than sorry.


You can also create a class that extends GridView to do this

[ToolboxData("<{0}:DecodedGridView runat='server'>")]
public class DecodedGridView : GridView
{
    protected override void Render(HtmlTextWriter writer)
    {
        for (var i = 0; i < Rows.Count; i++)
        {
            for (var j = 0; j < Rows[i].Cells.Count; j++)
            {
                if (Rows[i].RowType == DataControlRowType.DataRow
                    && !(((DataControlFieldCell)Rows[i].Cells[j]).ContainingField is CommandField))
                {
                    var encoded = Rows[i].Cells[j].Text;
                    Rows[i].Cells[j].Text = Context.Server.HtmlDecode(encoded);
                }
            }
        }
        base.Render(writer);
    }
}

You can then just change the GridViews to this where you want to have HTML encode removed.

Just declare the Assembly in a similar fashion:

<%@ Register TagPrefix="MyUI" Namespace="MyProject.UI" Assembly="MyProject" %>

Then call the GridView like so:

<MyUI:DecodedGridView ID="MyTableWithHtml" runat="server">
    <!-- All the normal GridView stuff -->
</MyUI:DecodedGridView>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜