views:

210

answers:

4

I'm binding an ASP.NET control to the result of a LINQ query. I'd like to HtmlEncode one of the properties of the contained objects before binding to the control, but I want to do it without altering the data because I do a DataContext.SubmitChanges() later on. How can this be done?

Code that won't work:

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();
A: 

Dummy me. I just need to HtmlEncode it within the OnItemDataBound() event.

tsilb
That would work as well...
J.13.L
A: 

Have two copies of the data:

from s in dc.SearchResults
orderby s.datetime descending
select new {
  Original = s,
  Encoded = Server.HtmlEncode(s.Query)
};
Richard
+1  A: 

Your could encode it when you do your binding...

<asp:YourDataBoundControl>
    <ItemTemplate>
        Query: <span><%# Server.HtmlEncode((string)Eval("Query")) %></span>
    </ItemTemplate>
</asp:YourDataBoundControl>
J.13.L
A: 

Or you could use HttpUtility.HtmlEncode('string');

Both are valid but the one above is available anywhere within an application easier than loading up HttpContext.Current.Server.HtmlEncode.

John_