在ASP.NET中的Response.Write函数中使用Alert

我有这样的数据库代码

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("

ERROR

"); }

它工作正常,但我想在catch函数中调用javascript警报函数。

我试过这个

 Response.Write("alert('ERROR');); 

但是有一个错误 在此处输入图像描述

如何在javascript alertfunction中显示错误消息?

尝试使用RegisterScriptBlock 。 链接示例:

 public void Page_Load(Object sender, EventArgs e) { // Define the name and type of the client scripts on the page. String csname1 = "PopupScript"; String csname2 = "ButtonClickScript"; Type cstype = this.GetType(); // Get a ClientScriptManager reference from the Page class. ClientScriptManager cs = Page.ClientScript; // Check to see if the startup script is already registered. if (!cs.IsStartupScriptRegistered(cstype, csname1)) { String cstext1 = "alert('Hello World');"; cs.RegisterStartupScript(cstype, csname1, cstext1, true); } // Check to see if the client script is already registered. if (!cs.IsClientScriptBlockRegistered(cstype, csname2)) { StringBuilder cstext2 = new StringBuilder(); cstext2.Append(" 

更换:

 Response.Write("); 

 Response.Write(""); 

换句话说,你在Response.Write语句的末尾错过了一个结束语。

值得一提的是,屏幕截图中显示的代码似乎正确包含结束双引号,但总体上最好的方法是使用ClientScriptManager.RegisterScriptBlock方法:

 var clientScript = Page.ClientScript; clientScript.RegisterClientScriptBlock(this.GetType(), "AlertScript", "alert('ERROR')'", true); 

这将使用标记包装脚本并将编写到页面中。

 string str = "Error mEssage"; Response.Write(""); 

你也可以使用Response.Write(“alert(’Error’)”);

以这种方式连接分隔斜杠和单词脚本的字符串。

 Response.Write(" 

用这个….

 string popupScript = " 

你可以简单地写

 try { //Your Logic and code } catch (Exception ex) { //Error message in alert box Response.Write(""); } 

它会工作正常