Skip to main content
 首页 » 编程设计

c#之ASP.NET 中的 Javascript 警报

2024年02月23日38soundcode

我想使用 Javascript Alert在我的 ASP.NET 页面中运行。

比如像这样;

Response.Write("<script language=javascript>alert('ERROR');</script>); 

但是,这是行不通的。

我在这里问我做错了什么,每个人都建议我使用 RegisterScriptBlock

ScriptManager.RegisterClientScriptBlock(this, this.GetType(), " ", "alert('ERROR')",true); 

但我不想使用它,因为它与 PostBack

一起工作

如果没有 PostBack,我怎么能做到这一点?

编辑:例如使用;

try 
{ 
    string strConnectionString = ConfigurationManager.ConnectionStrings["SqlServerCstr"].ConnectionString; 
 
    SqlConnection myConnection = new SqlConnection(strConnectionString); 
    myConnection.Open(); 
 
    string hesap = Label1.Text; 
    string musteriadi = DropDownList1.SelectedItem.Value; 
    string avukat = DropDownList2.SelectedItem.Value; 
 
    SqlCommand cmd = new SqlCommand("INSERT INTO AVUKAT VALUES (@MUSTERI, @AVUKAT, @HESAP)", myConnection); 
 
    cmd.Parameters.AddWithValue("@HESAP", hesap); 
    cmd.Parameters.AddWithValue("@MUSTERI", musteriadi); 
    cmd.Parameters.AddWithValue("@AVUKAT", avukat); 
    cmd.Connection = myConnection; 
 
    SqlDataReader dr = cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection); 
    Response.Redirect(Request.Url.ToString()); 
    myConnection.Close(); 
} 
catch (Exception) 
{ 
    Response.Write("<h2>ERROR</h2>"); 
} 

请您参考如下方法:

参见 a note from MSDN :

If you want to register a script block that does not pertain to partial-page updates, and if you want to register the script block only one time during initial page rendering, use the RegisterClientScriptBlock method of the ClientScriptManager class. You can get a reference to the ClientScriptManager object from the ClientScript property of the page.

所以,我认为ClientScriptManager.RegisterStartupScript方法是你需要的:

ClientScriptManager cs = Page.ClientScript; 
cs.RegisterClientScriptBlock( 
    this.GetType(),  
    " ",  
    @"<script language=javascript>alert('ERROR');</script>",  
    true 
);