asp.netquotesdatabinder

Databinder.Eval double quotes


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?


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.