how to bind javascript function with OnClientClick event with Eval?
Solution 1
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);
}
Solution 2
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.
Solution 3
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"))%>"**
Solution 4
You can do like OnClick='<%# "msgDisp(" + Eval("LocationId") + ");" %>'
ppp
Updated on July 09, 2022Comments
-
ppp almost 2 years
my link button -
<asp:LinkButton runat="server" ID="lbtnEdit" Text="edit" OnClientClick="javascript:msgDisp('<%# Eval(LocationId).toString() %>')" />
and the javascript msgDisp is-
<script type="text/javascript" language="javascript"> function msgDisp(lid) { alert(lid); } </script>
but it is not giiving LocationId in pop but the whole string <%#......%> is comin in popup message. How can I pass Eval values in javascript.
-
Shawn Kovac about 8 yearsif you want quotes around it like in
msgDisp('hello');
then you can use the HTML entity like:OnClientClick='<%# "msgDisp('" + Eval("LocationId") + "');" %>'
.