【问题标题】:GridView and Html EncodingGridView 和 Html 编码
【发布时间】:2011-02-22 15:15:59
【问题描述】:

我最近将客户的网站升级到 .NET 4,在此过程中我们发现现在 GridView 列的值会自动进行 HTML 编码。

他们在代码中广泛使用 HTML 字符串,因此我们必须将其关闭。我知道一个解决方案会遍历每一列并添加 HtmlEncode="false"。我的问题是 - 有没有办法将此设置为该应用程序中所有 GridView 列的默认值?

谢谢!

【问题讨论】:

    标签: asp.net gridview


    【解决方案1】:

    我找到了这个解决方案来解决这个问题。

     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);
                   }
            }
        }
    

    【讨论】:

      【解决方案2】:

      我认为默认情况下没有任何方法可以做到这一点,因为默认情况下这是作为安全措施放入的,因此开发人员需要考虑将其关闭。

      要解决这个问题,您需要逐列关闭它,或者您可以从GridView 继承一个新控件并将每列设置为默认值。然后,您可以搜索并用您的新控件替换 GridView。不过我不推荐这种方法。

      最好是询问应用程序中的每一列并将其关闭。它更安全,它让您真正考虑要在哪里打开 HTML / javascript 注入可能性的大门。安全总比后悔好。

      【讨论】:

        【解决方案3】:

        您还可以创建一个扩展 GridView 的类来执行此操作

        [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);
            }
        }
        

        然后,您可以将 GridViews 更改为您想要删除 HTML 编码的位置。

        只需以类似的方式声明大会:

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

        然后像这样调用 GridView:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-12-18
          • 2013-03-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-12-21
          • 1970-01-01
          相关资源
          最近更新 更多