DCSIMG
November 2009 - Posts - A Bit Lighter

A Bit Lighter

Simple things that may help you

November 2009 - Posts

Databinding: Eval with quotes in javascript

This is a common problem in ASP.NET databound controls. I have an ItemTemplate with some html. The html includes data bound parts like this:

 <a href='BLOCKED SCRIPTgoView(<%# Eval("Id") %>, <%# Eval("Type") %>)'>View</a>

What I want to achieve is when user clicks the View link, I want to call the javascript function goView and pass to it an integer Id and a string Type like this:

 goView(1, "Letter")

The problem is that my Type field comes from the database as Letter, with no quotes and my javascript call looks like

 goView(1, Letter)

which results in a javascript error.

Since the href already includes both single and double quotes, it is very hard to add any other quotes, whether with escaping as \”, \’ or not.

An easy way that worked to me was using the second parameter of Eval for formatting. This works:

<a href='BLOCKED SCRIPTgoView(<%# Eval("Id") %>, <%# Eval("Type", "\"{0}\"") %>)'>View</a>