【问题标题】:how to display alert by using serverside code in asp.net?如何在asp.net 中使用服务器端代码显示警报?
【发布时间】:2011-07-15 09:51:00
【问题描述】:

我想在单击按钮时执行以下代码,但是当我刷新页面时也会执行以下代码。我不想要那种行为。请帮帮我。

string str = "Are you sure, you want to Approve this Record?";
this.ClientScript.RegisterStartupScript(typeof(Page), "Popup", "ConfirmApproval('" + str + "');", true);

【问题讨论】:

  • 只是为了确定。您希望在单击按钮时首先获得确认消息。对吗?
  • 是的,但我不希望刷新页面时

标签: asp.net


【解决方案1】:

你的问题很不清楚。我假设您使用 ASP.NET C#,方法如下:

public static class ClientMessageBox
{

    public static void Show(string message, Control owner)
    {
        Page page = (owner as Page) ?? owner.Page;
        if (page == null) return;

        page.ClientScript.RegisterStartupScript(owner.GetType(),
            "ShowMessage", string.Format("<script type='text/javascript'>alert('{0}')</script>",
            message));

    }

}

然后,在您的页面中(记得引用上面的类):

protected void Page_Load(object sender, EventArgs e)
{
    ClientMessageBox.Show("Hello World", this);
}

看看它对你的情况是否有帮助。

【讨论】:

    【解决方案2】:

    您应该考虑将警报放入按钮的 OnClientClick 方法中。

    例如(添加您的其他必需属性和点击处理程序)

    <asp:Button ID="ApproveButton" runat="server" CausesValidation="False"
        OnClientClick="return confirm('Are you certain you want to approve this record?');" />
    

    如果用户点击确定,您的正常点击代码将运行,但如果他们取消该功能,则返回 false,因此不会处理点击。

    【讨论】:

    • 它在按钮单击时工作正常,但抱歉我使用的是 gridveiw 控件。当我在 gridview 控件上按下删除事件时,我想要确认消息是否可能
    • @user746909 看看这个答案stackoverflow.com/questions/2458351/…。我认为它解决了同样的问题
    【解决方案3】:

    OnClientClick 添加到您的按钮

    <asp:Button OnClientClick="return confirm('Are you sure, you want to Approve this Record?')" runat="server" />
    

    【讨论】:

      【解决方案4】:

      您应该使用 ma​​rto 的Chris W 的 代码。如果您想要一个干净的 HTML 标记,请使用它。

      protected void Page_Load(object sender, EventArgs e)
      {
          if (!IsPostBack)
          {
              string script = "javascript:return confirm('Are you certain you want to approve this record?');";
              //id of your button
              button.Attributes.Add("onclick", script):
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-04-04
        • 1970-01-01
        • 1970-01-01
        • 2013-10-10
        • 2013-10-03
        • 1970-01-01
        • 2017-05-03
        相关资源
        最近更新 更多