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

Son*_*nül 3 javascript c# asp.net

我有这样的数据库代码

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>");
}
Run Code Online (Sandbox Code Playgroud)

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

我试过这个

Response.Write("<script language=javascript>alert('ERROR');</script>);
Run Code Online (Sandbox Code Playgroud)

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

如何在javascript alert功能中显示错误消息?

Rob*_*Rob 12

更换:

Response.Write("<script language=javascript>alert('ERROR');</script>);
Run Code Online (Sandbox Code Playgroud)

Response.Write("<script language=javascript>alert('ERROR');</script>");
Run Code Online (Sandbox Code Playgroud)

换句话说,您在声明结尾"处错过了结束Response.Write.

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

var clientScript = Page.ClientScript;
clientScript.RegisterClientScriptBlock(this.GetType(), "AlertScript", "alert('ERROR')'", true);
Run Code Online (Sandbox Code Playgroud)

这将负责使用<script>标记包装脚本并将脚本编写到页面中.


Nei*_*ght 6

尝试使用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("<script type=\"text/javascript\"> function DoClick() {");
      cstext2.Append("Form1.Message.value='Text from client script.'} </");
      cstext2.Append("script>");
      cs.RegisterClientScriptBlock(cstype, csname2, cstext2.ToString(), false);
    }
}
Run Code Online (Sandbox Code Playgroud)