来自asp.net DataList内部按钮的JavaScript警报

时间:2016-06-15 17:48:47

标签: javascript c# asp.net twitter-bootstrap

如何从Asp.Net DataList中的按钮单击事件显示JavaScript警报或引导模式消息。 这是我的DataList:

     <asp:DataList ID="dListProduct" runat="server" RepeatColumns="4" OnItemCommand="dListProduct_ItemCommand" AutoPostBack="true">
    <ItemTemplate>
        <div>
            <table class="table-responsive" border="1">
                <tr>
                     <td>
                          <asp:Label runat="server" Text="Id" ></asp:Label><asp:Label ID="lblPId" runat="server" Text='<%# Eval("Product_Id")%>' Visible="true"></asp:Label>
                    </td>
                </tr>
                <tr>
                     <td>
                         <asp:Button id="btnAddtoCart" runat="server" Text="Add to Cart" CommandName="save" CommandArgument="save" OnClick="btnAddtoCart_Click"/>
                    </td>
                </tr>
            </table>
        </div>
    </ItemTemplate>
</asp:DataList>

以下是代码:

 protected void dListProduct_ItemCommand(object source, DataListCommandEventArgs e)
        {
            if (e.CommandName == "save")
            {
                Label Id = (Label)e.Item.FindControl("lblPId");
                Label Name = (Label)e.Item.FindControl("lblProductName");
                Label Stock = (Label)e.Item.FindControl("lblStock");
                Label Price = (Label)e.Item.FindControl("lblPrice");
                if (Stock.Text.Equals("0"))
                    return;

                bool check = false;

                foreach (Cart c in GenericCart.cart)
                {
                    if (c.ProductId == Convert.ToInt64(Id.Text))
                    {
                        c.Qty += 1;
                        c.Total = (c.Price * c.Qty);
                        check = true;
                        Response.Write("<script>alert('Hello');</script>");
                        break;
                    }
                }
                if (!check)
                {
                    Cart c = new Cart();
                    c.ProductId = Convert.ToInt64(Id.Text);
                    c.ProductName = Name.Text;
                    c.Qty = 1;
                    c.Price = (float)Convert.ToDecimal(Price.Text);
                    c.Total = (float)Convert.ToDecimal(Price.Text);
                    GenericCart.cart.Add(c);
                    Response.Write("<script>alert('Hello');</script>");
                }              
            }
        }

但此脚本消息永远不会显示。 有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

如果您希望在代码隐藏之前触发警报,或者在代码隐藏中使用OnClientClick来注册要在回发完成后执行的javascript函数,则可以在按钮上使用Page.RegisterStartupScript属性。< / p>

MSDN article on usage of RegisterStartupScript