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

时间:2011-02-23 09:06:32

标签: c# javascript 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>");
}

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

我试过这个

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

但是有一个错误enter image description here

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

7 个答案:

答案 0 :(得分:12)

替换:

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

使用

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

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

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

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

这将使用<script>标签包装脚本并将脚本写入页面。

答案 1 :(得分: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);
    }
}

答案 2 :(得分:3)

string str = "Error mEssage";
Response.Write("<script language=javascript>alert('"+str+"');</script>");

答案 3 :(得分:0)

您也可以使用 回复于( “警报( '错误')”);

答案 4 :(得分:0)

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

Response.Write("<script language='javascript'>alert('Especifique Usuario y Contraseña');</" + "script>");

答案 5 :(得分:0)

使用此....

 var httpClient = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true, PreAuthenticate = true });
        httpClient.DefaultRequestHeaders.Accept.Clear();
        httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        var result = string.Empty;
        HttpResponseMessage httpResponceMessage = null;
        ViewApplicationDiagnostics.LogTrace("GetTags Request URL is " + path);

        try
        {
            httpResponceMessage = await httpClient.GetAsync(path, cancellationTokenSourceForTagDetails.Token);
            //httpResponceMessage = await httpClient.GetAsync(path);

            if (httpResponceMessage.IsSuccessStatusCode)
            {
                result = await httpResponceMessage.Content.ReadAsStringAsync();
            }
            else
            {
                ViewApplicationDiagnostics.LogWarning("Request failed, status code is = " + httpResponceMessage.StatusCode);
                throw new Exception("Request failed with HTTP status code " + httpResponceMessage.StatusCode);
            }

        }
        catch (TaskCanceledException ex)
        {
            ViewApplicationDiagnostics.LogTrace(ex.ToString());
            throw ex;
        }

答案 6 :(得分:-2)

你可以简单地写

try
 {
    //Your Logic and code
 }
 catch (Exception ex)
 {
    //Error message in  alert box
    Response.Write("<script>alert('Error :" +ex.Message+"');</script>");
 }

它会正常工作