代码之家  ›  专栏  ›  技术社区  ›  tsilb

htmlencode不改变绑定数据的iQueryable内的字符串

  •  1
  • tsilb  · 技术社区  · 15 年前

    我正在将ASP.NET控件绑定到Linq查询的结果。我希望在绑定到控件之前对所包含对象的一个属性进行htmlencode,但我希望在不更改数据的情况下进行此操作,因为稍后我将执行DataContext.SubmitChanges()。怎么能做到?

    不起作用的代码:

    var ds = (from s in dc.SearchResults
        orderby s.datetime descending
        select s)
        .Take(int.Parse(ConfigurationManager.AppSettings["RecentItemQty"]));
    foreach (SearchResult sr in ds)
        sr.Query = Server.HtmlEncode(sr.Query);
    rSearches.DataSource = ds;
    rSearches.DataBind();
    
    4 回复  |  直到 15 年前
        1
  •  2
  •   bytebender    15 年前

    你可以在绑定时对其进行编码…

    <asp:YourDataBoundControl>
        <ItemTemplate>
            Query: <span><%# Server.HtmlEncode((string)Eval("Query")) %></span>
        </ItemTemplate>
    </asp:YourDataBoundControl>
    
        2
  •  0
  •   tsilb    15 年前

    假我。我只需要在onitemdatabound()事件中对其进行htmlencode。

        3
  •  0
  •   Richard    15 年前

    有两份数据副本:

    from s in dc.SearchResults
    orderby s.datetime descending
    select new {
      Original = s,
      Encoded = Server.HtmlEncode(s.Query)
    };
    
        4
  •  0
  •   John_    15 年前

    或者可以使用httputility.htmlencode(“string”);

    两者都是有效的,但在应用程序中的任何地方都可以使用上述方法,这比加载httpcontext.current.server.htmlencode更容易。