JJ.
JJ.

Reputation: 9950

What is the correct way to set up and display a JavaScript alert message in ASP .NET?

I'm completely new to working with JavaScript in ASP .NET so bear with me.

Say I have the following:

protected void btnCreateReplication_Click(object sender, EventArgs e)
{
   try
   {
      doSomething();
   }
   catch (Exception ex)
   {
      //How do I display the error? I know if I were in WinForms, I could just do this:
      MessageBox.Show(ex.Message); 
   }
}

First question:

  1. Should I put all of my JavaScript code in a .js file in my ASP .NET solution?
  2. If so, how do I call an alert message from the .js file?
  3. If not, how do I call an alert message instead of the MessageBox.Show?

Upvotes: 0

Views: 300

Answers (3)

user704988
user704988

Reputation: 436

Another helpful way to show JavaScript alerts would be to use OnClientClick in .ASPX page. This is similar to OnClick for ASP Classic if you are familiar with ASP.

OnClientClick="alert('Are you sure you want to delete this user?');"

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.onclientclick.aspx

This may not be helpful for you for above code but can use to show other simple alerts.

Upvotes: 0

Brett Weber
Brett Weber

Reputation: 1907

as Dave said, using the tScript.RegisterClientScriptBlock method, you can inject the javascript into your page and have it run.

If you want to make the alert a bit more complex, it is cleaner to use a StringBuilder to set up the script.

Here, a link! http://msdn.microsoft.com/en-us/library/asz8zsxy.aspx

Upvotes: 1

Dave Zych
Dave Zych

Reputation: 21887

You'll have to use the Page.ClientScript.RegisterClientScriptBlock method.

string script = "alert('We had an error')";
Page.ClientScript.RegisterClientScriptBlock(GetType(), 
    "myErrorKey", script, true);

RegisterClientScriptBlock takes a type, a key to see if the script block is already registered, the script, and a boolean indicating whether the method should add the script tags, or if you're string script variable already includes them.

Upvotes: 2

Related Questions