I need to return a confirmation message to OnClientClick event. The problem is I have to get the message from stored procedure, and I don't seem to call my function right.
<asp:ImageButton
OnClientClick="return confirm(<%# GetConfirmExportMessage()%>);"
OnClick="btnExportRed_Click"
runat="server"
ImageUrl="~/Images/excel_red.gif"
ID="btnExportRed"
AlternateText="Export all records!"/>
My code behind:
public string GetConfirmExportMessage()
{
string xmlFilterForExport = Parameters.ToString().Split('+')[4].Trim();
string alertMessage = companiesSearcher.GetAlertMessage(xmlFilterForExport, 1, null, null, IdSegment, 1, Convert.ToInt32(RoDB2004.BLL.clsUsers.UserID));
return alertMessage;
}
Try using equal sign instead of pound (and don't forget your single quotes).
OnClientClick="return confirm('<%= GetConfirmExportMessage()%>');"
However, if you're ImageButton is located inside a DataGrid or GridView, the server-side code will not be evaluated and will yeield an alert saying <%= GetConfirmExportMessage()%> instead of the real message.
To get around this problem (and to increase performance, throughput, etc.), output your message once to a variable, then alert the contents of the variable.
<script language="JavaScript">
var myMessage = '<%= GetConfirmExportMessage()%>';
</script>
Later, in the GridView...
OnClientClick="return confirm(myMessage);"
You save throughput by repeating a small variable name like "myMessage" and avoid repeating some big message. Also note, that the method GetConfirmExportMessage isn't called dozens of times increasing performance.
If your message is specific to data within a current row and not static like "Are you sure?", then I suggest you perform this operation inside the GridView's RowDataBound event. You'll have full access to the ImageButton and to the data the current row is binding to, which makes it very easy to setup server-side. Check out the FindControl() method, or if you know the exact location, just reference it and unbox the object.
protected void gvMyGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
ImageButton ibtn = (ImageButton)e.Row.FindControl("btnExportRed");
if(ibtn != null)
{
ibtn.ClientClick = "return confirm('" + GetConfirmExportMessage() + "');";
}
}
}
As an alternative solution, maybe you should look into WebMethods, AJAX and jQuery. This solution is probably the better one because the data is not sent to the client and only retrieved when necessary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With