0

I am using this code from w3schools: TryIt

How can i integrate it with asp:LinkButton or asp:Button using OnClientClick, while onClick is executing the server code.

GXCPL.Official
  • 267
  • 3
  • 19
  • "onClick is executing the server code" like ajax call or what? If you are causing postback, it will not directly work. – Amit Kumar Singh Sep 26 '17 at 10:57
  • Yes onClick is executing the server code and doing a postback. What I am trying to do is, submit a password reset form. I need to show error mesages, such as, Old password does not match/ New password and Confirm password do not match, etc. and that message needs to be shown in the snack bar. – GXCPL.Official Sep 26 '17 at 11:03
  • @Amit any heads up?? – GXCPL.Official Sep 27 '17 at 12:40
  • You can set up a public field from asp.net when your postback is done. That field can be string type. If it is not blank, snackbar will be shown. Then, read that value into javascript. Inside $(document).ready call your myFunction(), with the message if message is not empty. – Amit Kumar Singh Sep 27 '17 at 14:07
  • If it is partial postback, you can see this link and alter the call for document.ready to call a function which will load your snackbar. https://stackoverflow.com/questions/9586903/document-ready-is-not-working-after-postback – Amit Kumar Singh Sep 27 '17 at 14:13

1 Answers1

2

Almost a year late to the party, but I've just implemented the same snackbar.

It needs an UpdatePanel and you need to register a client script block on your event handler:

<asp:UpdatePanel runat="server" ID="UpdatePanel1">
    <ContentTemplate>
        <div>
            <asp:Button runat="server" ID="ShowSnackbar" Text="Show Snackbar" OnClick="ShowSnackbar_Click" />
        </div>

        <div id="snackbar">
            <asp:Label runat="server" ID="Snack" />
        </div>
    </ContentTemplate>
</asp:UpdatePanel>

The codebehind was tricky but it works. On page load, create a string that contains the javascript, then use that string value to register your script block...

private string snackbarScript;

protected void Page_Load(object sender, EventArgs e)
{
    snackbarScript = GenerateSnackbarJS();
}
private string GenerateSnackbarJS()
{
    var sb = new StringBuilder();
    sb.AppendLine("var x = document.getElementById('snackbar');");
    sb.AppendLine("x.className = 'show';");
    sb.AppendLine("setTimeout(function(){ x.className = x.className.replace('show', ''); }, 3000);");
    return sb.ToString();
}

protected void ShowSnackbar_Click(object sender, EventArgs e)
{
    Snack.Text = "Here's the snackbar";
    ScriptManager.RegisterClientScriptBlock(this.Page, this.Page.GetType(), "snackbar", snackbarScript, true);
}
Ortund
  • 8,095
  • 18
  • 71
  • 139