Nathan Kamenar Nathan Kamenar - 1 year ago 75
C# Question

Doing Eval in OnClientClick

I am having a problem using a databinding Eval in a OnClientClick and I can't find a way to make this bind properly. Here is my code

<asp:LinkButton runat="server" ID="ItemMenuBtn" CssClass="ui-button ui-widget ui-corner-all" OnClientClick='OpenItemMenu(<%# Eval("NotificationData") %>);return false;'>
<i class="fa fa-lg fa-bars" aria-hidden="true"></i>

I expect the output to be something like:

<a onclick="OpenItemMenu({JSON notification data here});return false;" id="some id" class="ui-button ui-widget ui-corner-all">

But instead I am getting:

<a onclick="OpenItemMenu(&lt;%# Eval(&quot;NotificationData&quot;) %>);return false;" id="ctl00_m_g_28e3d385_2509_4d3a_9c53_1d17b87a802b_gvNoteworthyItems_ctl02_ItemMenuBtn" class="ui-button ui-widget ui-corner-all" href="javascript:__doPostBack('ctl00$m$g_28e3d385_2509_4d3a_9c53_1d17b87a802b$gvNoteworthyItems$ctl02$ItemMenuBtn','')">

So my questions are:

  1. Why doesn't the eval seem to be working at all?

  2. Why is everything for the on client click encoded like that?

  3. Why is that postback being placed in the href of the link? As you can see in the on client click I don't want a postback as this button opens a dialog and passes data to it.

Answer Source

For OnClientClick, you can try:

OnClientClick='<%# string.Format("OpenItemMenu(\"{0}\"); return false", Eval("NotificationData")) %>'

If the LinkButton is not in a databound control, you have to call DataBind to ensure that the data binding expression is evaluated:

protected void Page_Load(object sender, EventArgs e)

By default, a click on the LinkButton triggers a postback with the help of __doPostBack. Returning false in the OnClientClick event handler cancels that postback.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download