fable fable - 23 days ago 6
Javascript Question

Response.Write JavaScript alert does not show anything

I want to show a javascript message on server side but Response.Write does not work without any error.

This is my code;

if (aktifmi == "0")
{
cmd = new SqlCommand("select * from dh where person_id=" + person_id + ";");
cmd.CommandType = CommandType.Text;
cmd.Connection = conn;
int ds= (int)cmd.ExecuteScalar();
if (ds!= 0)
{
Response.Write("<script language=javascript>alert('ERROR');</script>");

}
}
else { }


How can I show this message? What is my fault?

Answer

Depends on when your code is executed (e.g. during OnLoad vs. PreRender vs. OnInit). You can't just emit script onto the page any time you want and expect it to work. Script has to appear in certain parts of the page.

If you want to tell ASP.NET to put a script on the page that will reliably run when the page is loaded, consider using something like ClientScriptManager.RegisterStartupScript, or Page.RegisterStartupScript, which are designed for this purpose.

if (aktifmi == "0")
{
    cmd = new SqlCommand("select * from dh  where person_id=" + person_id + ";");
    cmd.CommandType = CommandType.Text;
    cmd.Connection = conn;
    int ds= (int)cmd.ExecuteScalar();
    if (ds!= 0)
    {
        this.RegisterStartupScript("DisplayError","<script language=javascript>alert('ERROR');</script>");
    } 
}