Home > Enterprise >  Toastr notifications after ImageButton is Clicked C# aspx
Toastr notifications after ImageButton is Clicked C# aspx

Time:06-04

I am using .aspx in c# for creating food ordering system. Now my problem is in the menu part where I need to show toastr notications after I cliked this Image button.

<asp:ImageButton ID="btnAdd" runat="server" BorderStyle="None" Height="52px"  ImageUrl="~/assets/img/Cart.png" Width="151px" CommandName="AddtoCart" />

Now, I've tried using toastr from NuGet packages

<link href="content/toastr.css" rel="stylesheet" />
<script src="Scripts/toastr.js"></script>
    
    <script type="text/javascript">
        $(function () {
            $("#btnAdd").click(function () {
                toastr["success"]("Items added To Cart")

                toastr.options = {
                    "closeButton": true,
                    "debug": false,
                    "newestOnTop": false,
                    "progressBar": false,
                    "positionClass": "toast-top-right",
                    "preventDuplicates": false,
                    "onclick": null,
                    "showDuration": "300",
                    "hideDuration": "1000",
                    "timeOut": "5000",
                    "extendedTimeOut": "1000",
                    "showEasing": "swing",
                    "hideEasing": "linear",
                    "showMethod": "fadeIn",
                    "hideMethod": "fadeOut"
                }
            });



        });
    </script> 

My problem is that alert('') only works for this script not for the toastr, but the toastr works if I create a non runat='server' button, like this one <button id="add">Add to Cart</button>

But doesn't work in

 <asp:Button ID="test"  Text="Test" runat="server"  />

and

<asp:ImageButton ID="btnAdd" runat="server" BorderStyle="None" Height="52px"  ImageUrl="~/assets/img/Cart.png" Width="151px" CommandName="AddtoCart" />

whom is inside the

<form  runat="server">
</form>

CodePudding user response:

I am adding this to make understand what could be one of the reason.

  1. You might be using Master Pages or User Control which will change the ID #btnAdd which you are referring the javascript. Solution could be use the clientIdMode = static it will not change the ID of the control. But look for duplicate Id issue.

  2. Normally server controls have a server methods which cause postback in this case you client script will not work. So you need to consider that what do you want to do with that. OnClientClick is the method which I remember used for client side funcaiton.

CodePudding user response:

Pheww, just found a solution for my question, here it is. You can put this code in the master page content head or aspx content head:

<script type="text/javascript" src="//cdn.jsdelivr.net/jquery/1/jquery.min.js"></script>

 <link media="screen" rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/css/toastr.css" />

    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/2.0.1/js/toastr.js"></script>



  <script type="text/javascript">

      function success(msg) {

          toastr.options = {
              "closeButton": true,
              "debug": false,
              "newestOnTop": false,
              "progressBar": false,
              "positionClass": "toast-top-right",
              "preventDuplicates": false,
              "onclick": null,
              "showDuration": "300",
              "hideDuration": "1000",
              "timeOut": "5000",
              "extendedTimeOut": "1000",
              "showEasing": "swing",
              "hideEasing": "linear",
              "showMethod": "fadeIn",
              "hideMethod": "fadeOut"
          }

          toastr.success(msg, "Success");

          return false;

      }



  </script>
    
  <script type="text/javascript">

      function error(msg) {

          toastr.options = {
              "closeButton": true,
              "debug": false,
              "newestOnTop": false,
              "progressBar": false,
              "positionClass": "toast-top-right",
              "preventDuplicates": false,
              "onclick": null,
              "showDuration": "300",
              "hideDuration": "1000",
              "timeOut": "5000",
              "extendedTimeOut": "1000",
              "showEasing": "swing",
              "hideEasing": "linear",
              "showMethod": "fadeIn",
              "hideMethod": "fadeOut"
          }

          toastr.error(msg, "Error");

          return false;

      }



  </script>

Plus put this code in the aspx.cs like this one

protected void Test_Click(object sender, EventArgs e){
 ScriptManager.RegisterStartupScript(this, typeof(Page), "Success", "<script> success('Item added to Cart')</script>", false);
}

Also this is also compatible with datalistitems with buttons or image button like this one:

if (e.CommandName.Equals("AddtoCart"))
            {
                img = (Image)e.Item.FindControl("Img") as Image;
                name = (Label)e.Item.FindControl("lblProdName");
                price = (Label)e.Item.FindControl("lblProdPrice");
                stock = (Label)e.Item.FindControl("lblProdStock");
                tx = (TextBox)e.Item.FindControl("txtQty");

                String n = name.Text.Trim();
                String p = price.Text.Trim();


                if (Session["Username"] == null)
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "swal('You must Login first!','Redirecting to Login......', 'error').then((value) => { window.location ='Login.aspx'; });", true);
                }
                else
                {
                    
                    if (tx.Text == null || tx.Text == "0" || tx.Text == "")
                    {
                       // ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "swal('Error', 'Select Quantity!', 'error');", true);
                        ScriptManager.RegisterStartupScript(this, typeof(Page), "Success", "<script> error('Select Quantity')</script>", false);
                    }

                    else if (ValueExist(n))//Check if item exist on cart
                    {
                       // ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "swal('Error', 'Item already in Cart!', 'error');", true);
                        ScriptManager.RegisterStartupScript(this, typeof(Page), "Success", "<script> error('Item already in Cart')</script>", false);
                    }
                    else
                    {
                        int s = Int32.Parse(stock.Text);
                        int q = Int32.Parse(tx.Text);
                        string username = session.Text;
                        int total = Int32.Parse(p) * q;
                        if (q > s)//Checks if stocks is enough
                        {
                            //ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "swal('Error', 'Not Enough Stocks!', 'error');", true);
                            ScriptManager.RegisterStartupScript(this, typeof(Page), "Success", "<script> error('Not Enough Stocks')</script>", false);
                        }
                        else
                        {
                            //insert
                            String str = "insert into Cart values(@user, @img, @name, @qty, @price, @tprice)";
                            con.Open();
                            SqlCommand cmd = new SqlCommand(str, con);
                            cmd.Parameters.AddWithValue("@user", username);
                            cmd.Parameters.AddWithValue("@img", img.ImageUrl);
                            cmd.Parameters.AddWithValue("@name", n);
                            cmd.Parameters.AddWithValue("@qty", q);
                            cmd.Parameters.AddWithValue("@price", p);
                            cmd.Parameters.AddWithValue("@tprice", total);
                            cmd.ExecuteNonQuery();
                            

                            //  Response.Redirect("Menu.aspx");
                            SqlCommand cmd1 = new SqlCommand("SELECT COUNT(*) FROM Cart WHERE Username=@user", con);
                            cmd1.Parameters.AddWithValue("@user", session.Text);
                            Int32 count = (Int32)cmd1.ExecuteScalar();
                            CartItems.Text = count.ToString();
                            noreload.Update();
                            ScriptManager.RegisterStartupScript(this, typeof(Page), "Success", "<script> success('Item added to Cart')</script>", false);
                            con.Close();
                        }
                    }


                }
            }

Yow thanks for the help guys

  • Related