Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use HtmlEncode with TemplateFields, Data Binding, and a GridView

I have a GridView bound to an ObjectDataSource. I've got it supporting editing as well, which works just fine. However, I'd like to safely HtmlEncode text that is displayed as we do allow special characters in certain fields. This is a cinch to do with standard BoundFields, as I just set HtmlEncode to true.

But in order to setup validation controls, one needs to use TemplateFields instead. How do I easily add HtmlEncoding to output this way? This is an ASP.NET 2.0 project, so I'm using the newer data binding shortcuts (e.g. Eval and Bind).

What I'd like to do is something like the following:

<asp:TemplateField HeaderText="Description">     <EditItemTemplate>         <asp:TextBox ID="TextBoxDescription" runat="server"                      Text='<%# System.Web.HttpUtility.HtmlEncode(Bind("Description")) %>'                      ValidationGroup="EditItemGrid"                      MaxLength="30" />         <asp:Validator ... />     </EditItemTemplate>     <ItemTemplate>         <asp:Label ID="LabelDescription" runat="server"                    Text='<%# System.Web.HttpUtility.HtmlEncode(Eval("Description")) %>' />     </ItemTemplate> </asp:TemplateField> 

However, when I try it this way, I get the following error:

CS0103: The name 'Bind' does not exist in the current context

like image 363
Sean Hanley Avatar asked Feb 04 '09 17:02

Sean Hanley


People also ask

When should I use Htmlencode?

Any time you are trying to output data that could include untrusted html, you should use HTMLENCODE . Encodes text and merge field values for use in HTML by replacing characters that are reserved in HTML, such as the greater-than sign ( > ), with HTML entity equivalents, such as &gt; .

What is the use of Htmlencode?

The HTMLEncode method applies HTML encoding to a specified string. This is useful as a quick method of encoding form data and other client request data before using it in your Web application. Encoding data converts potentially unsafe characters to their HTML-encoded equivalent.

What does Httputility Htmlencode do?

Converts an object's string representation into an HTML-encoded string, and returns the encoded string.


1 Answers

This is now possible to do using the new HTML encoding databinding syntax introduced in ASP.NET 4.

You can simply use:

<%#: Eval("MyField") %> 

Or

<%#: Bind("MyField") %> 

Note the colon after the pound/hash sign It's as simple as that.

like image 84
pattermeister Avatar answered Sep 23 '22 21:09

pattermeister