how to bind javascript function with OnClientClick event with Eval? how to bind javascript function with OnClientClick event with Eval? asp.net asp.net

how to bind javascript function with OnClientClick event with Eval?


You can build the entire contents of OnClientClick as a string within the code brackets and it will output like you're expecting.

<asp:LinkButton runat="server" ID="lbtnEdit" Text="edit"     OnClientClick='<%# "msgDisp(" + Eval("LocationId") + ");" %>' /> 

This is assuming LocationId is a valid number- there are no quote marks to wrap your value when it renders, so outputting something like msgDisp(hello); is going to break. I don't know how to address that in this manner, so if you have to do that I would recommend setting OnClientClick server side during the ItemDataBound event. Here's what it would like where the parent is a Repeater control.

protected void notesRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e){    MyClass item = (MyClass)e.Item.DataItem;    LinkButton lbtnEdit = (LinkButton)e.Item.FindControl("lbtnEdit");    lbtnEdit.OnClientClick = string.Format("msgDisp('{0}');", item.LocationId);}


If you are getting your binding expression tags (<%# ... %>) rendered in the markup, it means your LinkButton is not initialized in a binding container. A binding container can be, as @lincolnk demonstrated, an Repeater or GridView item, a Calendar cell, etc. Also, you do not have to prefix your function call with "javascript:". The value of the OnClientClick property is rendered as the handler of the anchor's onclick event.


Looked everywhere on the net. Everyone says use CodeBehind. See my solution, which works even when my datavalue has a single quote in it like O'Neal.This will not work if your data item contains doublequotes. But works for what I needed it to do which was pass in a person's name.Note the backslashes inside the alert call.

OnClientClick="<%#string.Format("alert(\"{0}\"); return false; ", Eval("NAME"))%>"**