Question

I have a problem and I can't figure it out how to solve it. I search for solutions but they did not work. So, I have a Datalist with ItemTemplate. I need to add google analytics on onclick event to <a> tags. I tried to add the onclick event like

 onclick="_gaq.push(['_trackEvent', 'Homepage', 'Click on',<%#DataBinder.Eval(Container.DataItem,"URL")%>']);" <br />

but I get a yellow error screen with the message "..tag is not formatted correctly". I also tryed replacing double qoutes with &qout; but no success. I also tried

onclick='<%# string.Format("_gaq.push(['_trackEvent','Homepage','Click on last awarded company','{0}']);", DataBinder.Eval(Container.DataItem, "URL") %>' <br />

but this also not worked.
Have you got any idea how could I solve this problem?

Was it helpful?

Solution

You really should do this kind of complex databinding in the "OnItemDataBound" event in the code behind. Have a look at the relevant MSDN page.

<asp:DataList id="ItemsList" OnItemDataBound="Item_Bound" runat="server">

Code Behind:

public void Item_Bound(object sender, DataListItemEventArgs e)
{
 if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
 {
  // find your link
  HyperLink link = (HyperLink)e.Item.FindControl("MyFirstHyperLink");

  // so something nice with your link here, for example add attributes.
  string a = DataBinder.Eval(e.Item, "URL", "_gaq.push(['_trackEvent','Homepage','Click on last awarded company','{0}']);");
  link.Attributes.Add("onclick", a);
 }
}

disclaimer: I haven't actually tested this code so you might need to make adjustments here and there. It merely serves to give you an idea of the direction to go.

OTHER TIPS

Could you please try below?

<a  href="#" onclick="_gaq.push(['_trackEvent', 'Homepage', 'Click on','<%#DataBinder.Eval(Container.DataItem,\"URL\")%>']);">Test</a>

I've met the following scenario: I had to reuse some function that returns a collection of dynamic objects, from other assembly. Generally, there is a possibility to publish the dynamic object to other assembly, by using [assembly: InternalsVisibleTo("Some.Assembly")], because the dynamic objects are internal to their assembly. Not having the choice, I've tried the item data binding method solution to add the script, but dynamic objects are not accessible there, even if I used Eval. But Eval works in the markup, and there the quote/apostrophe problem occurs. My solution was HTML escaping:

onclick='<%# "doSomething(&apos;" + Eval("DataProperty") + "&apos;, this);"%>'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top