how to bind javascript function with OnClientClick event with Eval?

ppp picture ppp · Sep 30, 2010 · Viewed 46.6k times · Source

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.

Answer

lincolnk picture lincolnk · Sep 30, 2010

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);
}