2

I have a button and onclick is set to this method which should display a simple JS alert pop up window:

string message = "File is already open. <br>Please close the file and try again.";
    System.Text.StringBuilder sb = new System.Text.StringBuilder();
    sb.Append("<script type = 'text/javascript'>");
    sb.Append("window.onload=function(){");
    sb.Append("alert('");
    sb.Append(message);
    sb.Append("')};");
    sb.Append("</script>");
    ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", sb.ToString());

I have used the code above before and it has worked but not this time. The only difference is that I was using master pages for the other site and not for this one, and this one also has a timer going.

Is there anything JS related to load in the <head> of the aspx page?

protected void btnToCSV_Click(object sender, EventArgs e)
    {
        try
        {
            StreamWriter writer = new StreamWriter(@"\\server location\test.csv");

            Some writer.write stuff...

            writer.Close();
        }
        catch (Exception ex)
        {
            lblMessage.Visible = true;
            string message = "File is already open. Please close the file and try again.";
            ClientScript.RegisterClientScriptBlock(
               this.GetType(),
              "alert",
              string.Format("alert('{0}');", message),
              true);

        }
}
2
  • do you see any js error on the page? Commented Jun 29, 2012 at 17:37
  • How is the timer implemented for this? Commented Jun 29, 2012 at 17:39

2 Answers 2

3

Try with this simplyfied version

string message = "File is already open. <br>Please close the file and try again.";
ScriptManager.RegisterClientScriptBlock(
  UpdatePanel1, // replace UpdatePanel1 by your UpdatePanel id
  UpdatePanel1.GetType(), // replace UpdatePanel1 by your UpdatePanel id
  "alert", 
  string.Format("alert('{0}');",message), 
  true );
Sign up to request clarification or add additional context in comments.

9 Comments

That works thanks. But it doesnt recognise <br> as new line. What is the tag for that?
@user1468537: replace <br> by \n. Alert box doesn't understand html.
the code above works if I have it on button_click() on its own but if I put it in a catch field (which is still in a button_click() method) it no longer works. Any idea why? I can trace all the way through the catch section and it does enter.
try and catch. i suppose due to postback it never gets a chance to display it?
@user1468537: please show more code, not sure if I understand.
|
2

You are not encoding anything here:

sb.Append(message);

If the message is Hello Jean d'Arc (notice the single quote) you will end up with the following code:

alert('Hello Jean d'Arc');

I am leaving you imagine the result of this => a javascript error of course.

To fix this error make sure that you have properly encoded the argument. One way to do this is to JSON serialize it:

var serializer = new JavaScriptSerializer();
sb.AppendFormat("alert({0});", serializer.Serialize(message));

Also since you have already includeed the <script> tags, make sure that you pass false as last argument of the RegisterClientScriptBlock function to avoid adding them twice:

ClientScript.RegisterClientScriptBlock(
    this.GetType(), 
    "alert", 
    sb.ToString(), 
    false           // <!---- HERE
);

And here's how the full code might look like:

var message = "File is already open. <br>Please close the file and try again.";
var sb = new StringBuilder();
sb.Append("<script type=\"text/javascript\">");
sb.Append("window.onload=function() {");
var serializer = new JavaScriptSerializer();
sb.AppendFormat("alert({0});", serializer.Serialize(message));
sb.Append("};");
sb.Append("</script>");
ClientScript.RegisterClientScriptBlock(
    this.GetType(), 
    "alert", 
    sb.ToString(), 
    false
);

Another remark is that if you are doing this in an AJAX call you should use the ClientScript.RegisterStartupScript method.

3 Comments

While your advice is perfeclty valid for a generic scenario, the message in this case is harcoded and has no '.
I am just pointing out all the errors and flaws I see with this code. The fact that the message is hardcoded absolutely doesn't relieve you from the obligation to hardcode it. Because the next developer that comes by and simply changes this message will get very bad surprises :-) I am also pointing those flaws out because SO is a well referenced site where many developers come to seek knowledge. When doing code reviews I see so many people doing those mistakes that are at the origin of very hard to find bugs.
point taken, just wanted to remark that lack of encoding is not causing this problem. Your answer is very complete and appreciated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.