如何使用 C# 在 asp.net 中隐藏和显示警报

How to hide and display alert in asp.net using c#

所以我有一个简单的 asp.net 应用程序,当单击按钮时,我想根据用户的提交向用户发出成功警报或错误警报。 我遇到的问题是,虽然我能够隐藏我的消息,但我无法在单击 asp:button 时显示它。

这是我要隐藏的 bootstrap 警报:

<div class="alert alert-success collapse" role="alert">
                        <a href="#" class ="close" data-dismiss="alert">&times;</a>
                        This is a success alert—check it out!</div>

这是我用来尝试调用它的 C# 代码:

Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", 
                    "<script>$(document).ready(function(){ $('.alert-success').show(); " +
                    "$('.alert-danger'); }); </script>");

在网上找不到太多关于 c# 代码的信息,所以就这样解决了。 我的东西有什么问题,我怎样才能让它发挥作用?

您必须向按钮添加属性 ClientIDMode 并扩展 RegisterClientScriptBlock 中的代码,以便将侦听器附加到按钮。

ClientIDMode

The ClientID value is set to the value of the ID property. If the control is a naming container, the control is used as the top of the hierarchy of naming containers for any controls that it contains.

<asp:Button ID="button" runat="server" ClientIDMode="Static" Text="Button" />
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", 
                    @"<script>$(document).ready(function() {

  $('#button').click(function() {
    $('.alert-success').show();
  })

});</script>");

例子

$(document).ready(function() {

  $('#button').click(function() {
    $('.alert-success').show();
  })
  
});
.alert {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
<div>
  <div class="alert alert-success alert-dismissible" role="alert">
    <a href="#" class="close" data-dismiss="alert">&times;</a> This is a success alert—check it out!</div>
<!--That would be asp:button-->
<button id="button">Show Alert</button>
</div>