We help IT Professionals succeed at work.

Javascript alert boxes in ASP.Net code behind

SubbuUSA
SubbuUSA asked
on
Hello sir,

I want to display a javascript alert boxes after my save operation in code behind. then immediately I need to redirect the user to the default page. this is just to keep the user informed and no decisions are taking based on yes or no response.

either of the one not happenning for me.

thanks
 Subbu
Comment
Watch Question

Hi,
here's complete description of how to use it Using a generic Alert Class:-

using System.Web;
using System.Text;
using System.Web.UI;

/// <summary>
/// A JavaScript alert
/// </summary>
public static class Alert
{

/// <summary>
/// Shows a client-side JavaScript alert in the browser.
/// </summary>
/// <param name="message">The message to appear in the alert.</param>
public static void Show(string message)
{
   // Cleans the message to allow single quotation marks
   string cleanMessage = message.Replace("'", "\'");
   string script = "<script type="text/javascript">alert('" + cleanMessage + "');</script>";

   // Gets the executing web page
   Page page = HttpContext.Current.CurrentHandler as Page;

   // Checks if the handler is a Page and that the script isn't allready on the Page
   if (page != null && !page.ClientScript.IsClientScriptBlockRegistered("alert"))
   {
     page.ClientScript.RegisterClientScriptBlock(typeof(Alert), "alert", script);
   }
}
}

Demonstration

That class of only 30 lines of code enables us to add a JavaScript alert to any page at any time. Here is an example of a Button.Click event handler that uses the method for displaying status messages.

void btnSave_Click(object sender, EventArgs e)
{
   try
   {
     SaveSomething();
     Alert.Show("You document has been saved");
   }
   catch (ReadOnlyException)
   {
     Alert.Show("You do not have write permission to this file");
   }
}


Author

Commented:
Thanks buggycoder,

Your solution was very fast and I appreciate that, however has 2 errors saying semi colon expected two times.I am not sure where to put that.

 string script = "<script type="text/javascript">alert('" + cleanMessage + "');</script>";

change the 3rd line in the show function with this line:-

string script = "<script type='text/javascript'>alert('" + cleanMessage + "');</script>";

Just replaced " with '
hope this solves your problem

Author

Commented:
Hey Buggycoder,

You saved lot of my time. you get gold for it.

Thanks
Subbu
My Pleasure Subbu