I have database code like this
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>");
}
It works fine but what I want, in the catch function, is to call the javascript alert function.
I've tried this
Response.Write("<script language=javascript>alert('ERROR');</script>);
But there is an error
How can I show error message in javascript
alert
function?
This question is related to
c#
javascript
asp.net
You ca also use Response.Write("alert('Error')");
You can simply write
try
{
//Your Logic and code
}
catch (Exception ex)
{
//Error message in alert box
Response.Write("<script>alert('Error :" +ex.Message+"');</script>");
}
it will work fine
string str = "Error mEssage";
Response.Write("<script language=javascript>alert('"+str+"');</script>");
Replace:
Response.Write("<script language=javascript>alert('ERROR');</script>);
With
Response.Write("<script language=javascript>alert('ERROR');</script>");
In other words, you're missing a closing "
at the end of the Response.Write
statement.
It's worth mentioning that the code shown in the screenshot appears to correctly contain a closing double quote, however your best bet overall would be to use the ClientScriptManager.RegisterScriptBlock method:
var clientScript = Page.ClientScript;
clientScript.RegisterClientScriptBlock(this.GetType(), "AlertScript", "alert('ERROR')'", true);
This will take care of wrapping the script with <script>
tags and writing the script into the page for you.
Concatenate the string separating the slash and the word script in this way.
Response.Write("<script language='javascript'>alert('Especifique Usuario y ContraseƱa');</" + "script>");
Use this....
string popupScript = "<script language=JavaScript>";
popupScript += "alert('Please enter valid Email Id');";
popupScript += "</";
popupScript += "script>";
Page.RegisterStartupScript("PopupScript", popupScript);
Source: Stackoverflow.com