locked
client side msgbox with asp.net and ajax help RRS feed

  • Question

  • User1646142324 posted

    I was using a msgbox to get a user response but after some search found out that doesn't work on a webserver for getting and responding to client interaction.
    So I found this post and tried the method NC describes there. 

    http://forums.asp.net/t/1175290.aspx

    Now if I use an input tag my code behind wont find/recognize the id so I tried using a textbox that I hide onload of the page. I get the clientside messagebox but my actions that are needed when clicked on ok or cancel are not being done? Anyone has any more insight on this?

     

    Here are the code snippets:

    In Page_Load:
     

    If IsPostBack AndAlso Request("__EVENTTARGET") = "confirmValueVraagVerwijder" Then
    Me
    .Response.Write("confirmValueVraagVerwijder.Text: " + confirmValueVraagVerwijder.Text + "<br>")

    If confirmValueVraagVerwijder.Text = "true" Then
    ' User answered OK
    Dim objController As KlantendienstController = New KlantendienstController
    objController.DeleteVraagCategorieV(lstVragen.SelectedValue)
    objController.DeleteVraag(lstVragen.SelectedValue)
    lstVragen.Items.Remove(lstVragen.SelectedItem)
    lblMessage.Text = "De bewerking werd successvol doorgevoerd."
    'Page.ClientScript.GetPostBackEventReference(confirmValueVraagVerwijder, String.Empty)

    Else
    ' User answered Cancel
    lblMessage.Text = "De vraag werd niet verwijderd."
    End If

      

    Then in my button onclick:

                        

    Dim scriptString As String = "<script language=JavaScript>" + Environment.NewLine
    ' Store the confirm's return in the hidden control...
    scriptString += "document.getElementById('" + confirmValueVraagVerwijder.ClientID + "').value = " + Environment.NewLine
    scriptString += "
    confirm('Are you sure?');" + Environment.NewLine
    ' Do a new PostBack...

    scriptString += Page.ClientScript.GetPostBackEventReference(confirmValueVraagVerwijder, String.Empty) + ";" + Environment.NewLine
    scriptString += "</"
    scriptString += "script>"

    Page.ClientScript.RegisterStartupScript(Me.GetType, "ConfirmScriptVraagVerwijder", scriptString)

     

    Thanks in advance for the assistance. 

    Thursday, January 31, 2008 5:01 AM

Answers

  • User798903548 posted

    There were so many responses on the link that you provided, that I decided to re-post the solution.

    As DisturbedBuddha posted the easiest way, as long as no server-side processing is required PRIOR to the confirmation message is:

    private void Page_Load(object sender, System.EventArgs e)
    {
     Button1.Attributes.Add("onclick", "return window.confirm('Are you sure?');");
    }

    If however you need to do server-side processing PRIOR to the confirmation message:

    private void Button1_Click(object sender, System.EventArgs e)
    {
     bool isConfirmNeeded = false;
     string confirmMessage = string.Empty;

     // All server side execution goes here and set isConfirmNeeded to true,
     // and create the confirmMessage text, if user confirmation is needed.

     if ( isConfirmNeeded )
     {
      System.Text.StringBuilder javaScript = new System.Text.StringBuilder();

      javaScript.Append("\n<script type=text/javascript>\n");
      javaScript.Append("<!--\n");

      javaScript.Append("var userConfirmation = window.confirm('" + confirmMessage + "');\n");
      javaScript.Append("__doPostBack('UserConfirmationPostBack', userConfirmation);\n");

      javaScript.Append("// -->\n");
      javaScript.Append("</script>\n");

      RegisterStartupScript(scriptKey, javaScript.ToString());
     }
    }

    private void Page_Load(object sender, System.EventArgs e)
    {
     // Insure that the __doPostBack() JavaScript is added to the page...
     this.GetPostBackEventReference(this, string.Empty);

     if ( this.IsPostBack )
     {
      string eventTarget = (this.Request["__EVENTTARGET"] == null) ? string.Empty : this.Request["__EVENTTARGET"];
      string eventArgument = (this.Request["__EVENTARGUMENT"] == null) ? string.Empty : this.Request["__EVENTARGUMENT"];

      if ( eventTarget = "UserConfirmationPostBack" )
      {
       if ( eventArgument == "true" )
        // User said to go ahead and do it...
       else
        // User said NOT to do it...
      }
     }
    }

    Also, do NOT use Response.Write to render your JavaScript.

    NC...

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, January 31, 2008 11:02 AM
  • User-1465149523 posted

    Hi , Try this

    in Button1 

    If (isConfirmNeeded) Then

    Dim javaScript As System.Text.StringBuilder = New System.Text.StringBuilder()

     

    javaScript.Append("var userConfirmation = window.confirm('" + confirmMessage + "');")

    javaScript.Append("__doPostBack('UserConfirmationPostBack',userConfirmation);")

     

     ScriptManager .RegisterStartupScript( Page,Page.GetType, scriptKey, javaScript.ToString() ,true )

    End If

     

     

    in page load

    If (Page.IsPostBack) Then

    Dim eventTarget As String

    If (Page.Request("__EVENTTARGET") = Nothing) Then

    eventTarget = String.Empty

    Else

    eventTarget = Page.Request("__EVENTTARGET")

    End If

    Dim eventArgument As String

    If (Page.Request("__EVENTARGUMENT") = Nothing) Then

    eventArgument = String.Empty

    Else

    eventArgument = Page.Request("__EVENTARGUMENT")

    End If

    If (eventTarget = "UserConfirmationPostBack") Then

    If (eventArgument = "true") Then

    'User said to go ahead and do it...

    Label1.Text = "You clicked YES - added after confirm during page load"

    Else

    Label1.Text = "You clicked NO - added after confirm during page load"

    End If

    End If

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, February 13, 2008 4:06 PM
  • User798903548 posted

    It is same as your post NC1, do you remember I have posted for the similar type of problem then you replied me the answer, but as I am using AJAX in my application it did not work. but the same code is working in application where I did not use AJAX. So I was keep on trying by taking your code as base.

    I don't know the reason but when I removed the script tags and executed my application it worked fine.

    I think the reason might be AJAX is a combination of XML and Javascript ,that is why we don't need to mention script tags . Just I am guessing. If I use script tag in the code I am getting javascript runtime error. I may be wrong but the thing is my problem is solved.

    Thank you NC1...

    No that is because to render your script, you are using:
         ScriptManager.RegisterStartupScript( Page,Page.GetType, scriptKey, javaScript.ToString() ,true )

    That last argument (true) tells the method to add the script tags for you.

    To add your own script tags use:
         ScriptManager.RegisterStartupScript( Page,Page.GetType, scriptKey, javaScript.ToString() ,false)
    or just
         ScriptManager.RegisterStartupScript( Page,Page.GetType, scriptKey, javaScript.ToString())

    NC...

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, February 14, 2008 8:47 AM

All replies

  • User312496708 posted

    have a look at the following article which talks about the same topic

    http://msdn.microsoft.com/en-us/library/bb428868.aspx

    Thursday, January 31, 2008 7:17 AM
  • User-1684099974 posted

    Not to make this too simple, but why don't you just add the following: 

        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            Button1.Attributes.Add("onclick", "return confirm('Are you sure?');")
        End Sub
     

    If they click "yes", the server-side button click code executes.  If they click "no", it does not.  Simple as that.

    Thursday, January 31, 2008 9:29 AM
  • User798903548 posted

    There were so many responses on the link that you provided, that I decided to re-post the solution.

    As DisturbedBuddha posted the easiest way, as long as no server-side processing is required PRIOR to the confirmation message is:

    private void Page_Load(object sender, System.EventArgs e)
    {
     Button1.Attributes.Add("onclick", "return window.confirm('Are you sure?');");
    }

    If however you need to do server-side processing PRIOR to the confirmation message:

    private void Button1_Click(object sender, System.EventArgs e)
    {
     bool isConfirmNeeded = false;
     string confirmMessage = string.Empty;

     // All server side execution goes here and set isConfirmNeeded to true,
     // and create the confirmMessage text, if user confirmation is needed.

     if ( isConfirmNeeded )
     {
      System.Text.StringBuilder javaScript = new System.Text.StringBuilder();

      javaScript.Append("\n<script type=text/javascript>\n");
      javaScript.Append("<!--\n");

      javaScript.Append("var userConfirmation = window.confirm('" + confirmMessage + "');\n");
      javaScript.Append("__doPostBack('UserConfirmationPostBack', userConfirmation);\n");

      javaScript.Append("// -->\n");
      javaScript.Append("</script>\n");

      RegisterStartupScript(scriptKey, javaScript.ToString());
     }
    }

    private void Page_Load(object sender, System.EventArgs e)
    {
     // Insure that the __doPostBack() JavaScript is added to the page...
     this.GetPostBackEventReference(this, string.Empty);

     if ( this.IsPostBack )
     {
      string eventTarget = (this.Request["__EVENTTARGET"] == null) ? string.Empty : this.Request["__EVENTTARGET"];
      string eventArgument = (this.Request["__EVENTARGUMENT"] == null) ? string.Empty : this.Request["__EVENTARGUMENT"];

      if ( eventTarget = "UserConfirmationPostBack" )
      {
       if ( eventArgument == "true" )
        // User said to go ahead and do it...
       else
        // User said NOT to do it...
      }
     }
    }

    Also, do NOT use Response.Write to render your JavaScript.

    NC...

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, January 31, 2008 11:02 AM
  • User-154051931 posted

    If you have client-side validation that needs to execute before submitting the form, you will need to do it this way...

        Button1.Attributes.Add("onclick", "if(!confirm('Are you sure?')) return false;");
     
    Best regards...
    Thursday, January 31, 2008 12:54 PM
  • User1646142324 posted

    Thanks alot for the responses. I indeed need server side processing PRIOR to the confirmmessage and AFTER the confirmmessage after wich my controls on the page need to be updated So I will need the method of NC. Thanks alot for the update. I will be testing it monday and post then if I got it to work. Thanks for the help. 

    Friday, February 1, 2008 3:33 AM
  • User1646142324 posted

    Haven't got to testing it yet, other priority atm so will do next week. the scriptKey is just a name you can choose for the script right?

    How do I create another postback so my info on my page gets updated? after the user has said YES I do more processing and need to update the page.

    Thanks in advance.

     

    Wednesday, February 6, 2008 5:35 AM
  • User798903548 posted


    Haven't got to testing it yet, other priority atm so will do next week. the scriptKey is just a name you can choose for the script right?

    Yes scriptKey is just a name you choose for the script. It insures that the script is not added more than once.


    How do I create another postback so my info on my page gets updated? after the user has said YES I do more processing and need to update the page.

    The __doPostBack call, created in the server-side button click event handler, generates the PostBack which you catch in the Page_Load event handler.

    I do not see why you would need yet another PostBack. You would just do your update here:

    ...

    if ( eventArgument == "true" )
    {
     // User said to go ahead and do it...

     // Do any processing for a "Yes" response
    }
    else
    {
     // User said NOT to do it...

     // Do any processing for a "No" response
    }

    ...

    NC...

    Wednesday, February 6, 2008 7:46 AM
  • User1646142324 posted

     Don't really get it yet. Here is a little testpage I made but I am not getting any confirmmessage yet:

     In my Page_Load:

      

    Page.ClientScript.GetPostBackEventReference(Me, String.Empty)
                    If (Page.IsPostBack) Then
                        Dim eventTarget As String
                        If (Page.Request("__EVENTTARGET") = Nothing) Then
                            eventTarget = String.Empty
                        Else
                            eventTarget = Page.Request("__EVENTTARGET")
                        End If
    
                        Dim eventArgument As String
                        If (Page.Request("__EVENTARGUMENT") = Nothing) Then
                            eventArgument = String.Empty
                        Else
                            eventArgument = Page.Request("__EVENTARGUMENT")
                        End If
    
                        If (eventTarget = "UserConfirmationPostBack") Then
                            If (eventArgument = "True") Then
                                'User said to go ahead and do it...
                                Label3.Text = "You clicked YES - added after confirm during page load"
                            Else
                                Label3.Text = "You clicked NO - added after confirm during page load"
                            End If
                        End If
                    End If
     

    In my code behind button event:
      

    Dim isConfirmNeeded As Boolean = True
                Dim confirmMessage As String = "This is the message, yes or no"
                Dim scriptKey As String = "test"
    
                If (isConfirmNeeded) Then
                    Dim javaScript As System.Text.StringBuilder = New System.Text.StringBuilder()
    
                    javaScript.Append("\n<script type=text/javascript>\n")
                    javaScript.Append("<!--\n")
    
                    javaScript.Append("var userConfirmation = window.confirm('" + confirmMessage + "');\n")
                    javaScript.Append("__doPostBack('UserConfirmationPostBack', userConfirmation);\n")
    
                    javaScript.Append("// -->\n")
                    javaScript.Append("</script>\n")
                    Page.ClientScript.RegisterStartupScript(Me.GetType, scriptKey, javaScript.ToString())
                End If

     

    Thanks for you help. 

    Thursday, February 7, 2008 6:50 AM
  • User798903548 posted

    1. Are you using AJAX by chance?
    2. Is the JavaScript getting rendered (do a View Source with the page displayed in your browser and look towards the bottom).

    There is not much else that I have to go on here with the code that you have posted as it works for me.

    NC...

    Thursday, February 7, 2008 8:40 AM
  • User1646142324 posted

     Yes I am also using ajax. (would that be colliding with this?)

     The script at the bottom of the page when watching the source looks like this:

    <script type=text/javascript>\n<!--\nvar userConfirmation = window.confirm('This is the message, yes or no');\n__doPostBack('UserConfirmationPostBack', userConfirmation);\n// -->\n</script>
    .. and some more scripts are there aswell generated by dotnetnuke (it is a dotnetnuke module I am writing)  


     

    Thursday, February 7, 2008 10:49 AM
  • User798903548 posted

    The ScriptManager control manages script resources for ASP.NET AJAX pages. For more information, see http://www.asp.net/ajax/documentation/live/overview/ScriptManagerOverview.aspx

    I believe that you just need to change ClientScript to ScriptManager.

    NC...

    Thursday, February 7, 2008 10:55 AM
  • User1646142324 posted

    haven't got it to work yet but I have replaced the page.clientscript.registerstartupscript by the scriptmanager.registerstartupscript BUT I can't find an appropriate method of the scriptmanager for replacing clientscript.getpostbackeventreference.

    Any idea with what I need to replace this? 

    Friday, February 8, 2008 3:29 AM
  • User798903548 posted

    Calling ClientScript.GetPostBackEventReference (note the casing) just insures that the JavaScript __doPostBack is added to the HTML. I do not believe that it is in ScriptManager. Just a simple call in the Page_Load should be enough.

    NC...

    Friday, February 8, 2008 12:13 PM
  • User-1465149523 posted

    Hi , Try this

    in Button1 

    If (isConfirmNeeded) Then

    Dim javaScript As System.Text.StringBuilder = New System.Text.StringBuilder()

     

    javaScript.Append("var userConfirmation = window.confirm('" + confirmMessage + "');")

    javaScript.Append("__doPostBack('UserConfirmationPostBack',userConfirmation);")

     

     ScriptManager .RegisterStartupScript( Page,Page.GetType, scriptKey, javaScript.ToString() ,true )

    End If

     

     

    in page load

    If (Page.IsPostBack) Then

    Dim eventTarget As String

    If (Page.Request("__EVENTTARGET") = Nothing) Then

    eventTarget = String.Empty

    Else

    eventTarget = Page.Request("__EVENTTARGET")

    End If

    Dim eventArgument As String

    If (Page.Request("__EVENTARGUMENT") = Nothing) Then

    eventArgument = String.Empty

    Else

    eventArgument = Page.Request("__EVENTARGUMENT")

    End If

    If (eventTarget = "UserConfirmationPostBack") Then

    If (eventArgument = "true") Then

    'User said to go ahead and do it...

    Label1.Text = "You clicked YES - added after confirm during page load"

    Else

    Label1.Text = "You clicked NO - added after confirm during page load"

    End If

    End If

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, February 13, 2008 4:06 PM
  • User798903548 posted

    Hi , Try this

    in Button1 

    If (isConfirmNeeded) Then

    Dim javaScript As System.Text.StringBuilder = New System.Text.StringBuilder()

     

    javaScript.Append("var userConfirmation = window.confirm('" + confirmMessage + "');")

    javaScript.Append("__doPostBack('UserConfirmationPostBack',userConfirmation);")

     

     ScriptManager .RegisterStartupScript( Page,Page.GetType, scriptKey, javaScript.ToString() ,true )

    End If

     

     

    in page load

    If (Page.IsPostBack) Then

    Dim eventTarget As String

    If (Page.Request("__EVENTTARGET") = Nothing) Then

    eventTarget = String.Empty

    Else

    eventTarget = Page.Request("__EVENTTARGET")

    End If

    Dim eventArgument As String

    If (Page.Request("__EVENTARGUMENT") = Nothing) Then

    eventArgument = String.Empty

    Else

    eventArgument = Page.Request("__EVENTARGUMENT")

    End If

    If (eventTarget = "UserConfirmationPostBack") Then

    If (eventArgument = "true") Then

    'User said to go ahead and do it...

    Label1.Text = "You clicked YES - added after confirm during page load"

    Else

    Label1.Text = "You clicked NO - added after confirm during page load"

    End If

    End If

    Hema@sanofi,

    And how is that different from what was posted before? It looks as though you took my first post and converted it into VB.

    NC...

    Thursday, February 14, 2008 6:54 AM
  • User-1465149523 posted

    It is same as your post NC1, do you remember I have posted for the similar type of problem then you replied me the answer, but as I am using AJAX in my application it did not work. but the same code is working in application where I did not use AJAX. So I was keep on trying by taking your code as base.

    I don't know the reason but when I removed the script tags and executed my application it worked fine.

    I think the reason might be AJAX is a combination of XML and Javascript ,that is why we don't need to mention script tags . Just I am guessing. If I use script tag in the code I am getting javascript runtime error. I may be wrong but the thing is my problem is solved.

    Thank you NC1...

     

     

    Thursday, February 14, 2008 8:30 AM
  • User798903548 posted

    It is same as your post NC1, do you remember I have posted for the similar type of problem then you replied me the answer, but as I am using AJAX in my application it did not work. but the same code is working in application where I did not use AJAX. So I was keep on trying by taking your code as base.

    I don't know the reason but when I removed the script tags and executed my application it worked fine.

    I think the reason might be AJAX is a combination of XML and Javascript ,that is why we don't need to mention script tags . Just I am guessing. If I use script tag in the code I am getting javascript runtime error. I may be wrong but the thing is my problem is solved.

    Thank you NC1...

    No that is because to render your script, you are using:
         ScriptManager.RegisterStartupScript( Page,Page.GetType, scriptKey, javaScript.ToString() ,true )

    That last argument (true) tells the method to add the script tags for you.

    To add your own script tags use:
         ScriptManager.RegisterStartupScript( Page,Page.GetType, scriptKey, javaScript.ToString() ,false)
    or just
         ScriptManager.RegisterStartupScript( Page,Page.GetType, scriptKey, javaScript.ToString())

    NC...

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, February 14, 2008 8:47 AM
  • User-1465149523 posted
    Thank you
    Thursday, February 14, 2008 10:14 AM
  • User798903548 posted

    No problemo!

    NC...

     

    Thursday, February 14, 2008 10:25 AM
  • User1646142324 posted

    Thanks alot guys.

    Without the script tags I get the messagebox to show asking for input. I have used the VB version posted above and all is working perfect on a new page with nothing else...

    However when used on the site I am creating it is just one module on a page with many and it is not working. the messagebox is showing now but the code that needs to be executed when pressed yes or no is not. So something else on the page is messing it up. You got some suggestions where to look? I am using dotnetnuke with multiple custom made modules where some of them use ajax(ajaxcontroltoolkit). Probably a javascript that is interfering with this right? I'ts kinda impossible to post all the code cuz I have no idea where the source of my problem is atm. Thanks again for the assistance and if you have any more ideas let me know. Greetz.

    Friday, February 15, 2008 4:01 AM
  • User798903548 posted

    It is also impossible to help with the information given. Anything would be just a guess. I would start from starting from a simpler format and add modules back as things work.

    NC...

     

    Friday, February 15, 2008 7:19 AM
  • User1646142324 posted

    Yeah I will do so.

    Thanks alot for the help! 

    Monday, February 18, 2008 3:09 AM
  • User860067021 posted

    I'm using the NC code sucessufly.

    But, when the Confirm Dialog shows up, all controls in my page goes hide. Is there any way to show the Confirm dialog with all controls visible?

     Thanks

    Thursday, June 12, 2008 12:43 PM
  • User798903548 posted

    How are you outputting the JavaScript? If you are using Response.Write, that is your problem. Other then that, the controls on my test page all show, so I don't know what to tell you. Post some code maybe.

    NC...

     

    Friday, June 13, 2008 7:38 AM
  • User600651647 posted

    Hi,

    I have to show a message box with Yes/No  or Ok/Cancel button in the form load event.

    I need to store the answer of the user in a variable, because based on that answer, I have to process the remaining code. What is the best way to do this? I am using C#.

    Thanks,

    Friday, November 19, 2010 10:15 AM