user1285383
user1285383

Reputation: 73

How to show alert box in asp.net

I am showing alert box in my page, but after that my page is breaking down.

Response.Write("<script>alert('Selected items are removed successfully')</script>");

How to fix that?

Upvotes: 2

Views: 26116

Answers (3)

dodexahedron
dodexahedron

Reputation: 4657

Response.Write writes directly to the output stream, before the page is rendered. If you look at the resulting page code, you will see your output before any HTML. This breaks page state among other things.

What you most likely want is something like the RegisterStartupScript method, to write out a proper script block at the end of the page.

Link to documentation: http://msdn.microsoft.com/en-us/library/system.web.ui.clientscriptmanager.registerstartupscript.aspx

See @Claudio Redi's post for a code example of this method.

Upvotes: 2

Claudio Redi
Claudio Redi

Reputation: 68440

That's not the way to send javascript code to client on ASP.NET

You could use Page.ClientScript.RegisterStartupScript

 Page.ClientScript.RegisterStartupScript(
   this, 
   GetType(), 
   "ALERT", 
   "alert('Selected items are removed successfully')", 
   true);

In this case, you could also use Page.ClientScript.RegisterClientScriptBlock

 Page.ClientScript.RegisterClientScriptBlock(
   this, 
   GetType(), 
   "ALERT", 
   "alert('Selected items are removed successfully')", 
   true);

To understand differences between RegisterStartupScript and RegisterClientScriptBlock you could check here

Difference between RegisterStartupScript and RegisterClientScriptBlock?

You will also understand why they aren't always interchangeable.

Upvotes: 7

user652411
user652411

Reputation: 211

Here's the syntax that triggers javascript code during a webform post-back:

    Dim scVal As String
    scVal = "<script type='text/javascript'>"
    scVal = scVal & " alert('Selected items are removed successfully');</script>"
    ScriptManager.RegisterStartupScript(Me.Page, Me.GetType(), "temp", scVal, False)

Upvotes: 1

Related Questions