Solved

need help with ClientScript logic

Posted on 2007-04-09
21
337 Views
Last Modified: 2013-11-07
i  have the following logic in an onclick method for a button on my page - basically when someone clicks the button, I iterate through each row in the gridview to see whether the checkbox on that row has been selected, and if so, to update the row with some logic in this method... I wanted a confirm type alert to appear if one of the fields of the selected row was already pre-populated. I can't get the return confirm logic to work - no matter what the user clicks 'OK' or 'cancel', the update occurs. I'm missing something totally obvious but can't figure it out... can someone help?


Sub btnAssign (ByVal.....)
   For i as Integer = 0 to gridD.Rows.Count-1
     Dim cb as CheckBox = CType(gridD.Rows(i).FindControl("Checkbox"), CheckBox)
      If not gridD.Rows(i).Cells(8).Text = " " then
         ClientScript.RegisterStartupScript(Me.GetType(), "", String.Format("confirm('Warning!... Overwrite?');", true)
    end if
'update logic here....

0
Comment
Question by:acdagirl
  • 11
  • 10
21 Comments
 
LVL 23

Expert Comment

by:Christopher Kile
Comment Utility
First, if you want to avoid having an update occur, exit the function before you update.  Second, you want the warning to appear clientside within the same window instance in which you encounter the situation - in my opinion, you do NOT want to post back to the server before handling this.

Where is the button you are pressing?  Is it in the GridView, or elsewhere on the page?
0
 

Author Comment

by:acdagirl
Comment Utility
no - that's not the point. The client script is not letting me cancel or even exit the function - whatever I press on that alert button the end result is the same. What are you talking about posting back to the server? The code explicitly does not post back to the server when popping up the alert window? I just need to know how to make the clientscript work within the button click event - and if this is not possible how to handle this situation otherwise. The onclientclick event of the button will not work either as I need to implement a warning within the button click event that pops up a warning.

the button is external to the gridview, which is the way I need it. I do not want to implement a button wtihin the gridview for this - there are many working examples on the web for this.
0
 
LVL 23

Expert Comment

by:Christopher Kile
Comment Utility
Excuse me, please, but the code you showed us is server-side, not client-side, and can ONLY be executed after a postback (RegisterStartUpScript() is a member function of the Page object which is not available on the client, and you can NOT perform data updates from the client, only from the server).

Do you perform data entry within the grid?  How can you tell the difference between data that the user added and data that was "pre-populated"? (or are you modifying some fields, based on which other fields will get populated after the update is performed?).  

Also, what language are you using for your client-side scripting?  VBScript or Javascript?
0
 

Author Comment

by:acdagirl
Comment Utility
Let me rephrase my question. The gridview and updates are immaterial. My question is simply looking at this line any where within any if statement:
   ClientScript.RegisterStartupScript(Me.GetType(), "", String.Format("confirm('Warning!... Overwrite?');", true)
produces an alert window with OK/Cancel buttons. However, the OK/Cancel produce the same effect - How/where do I code the OK/Cancel logic. I'm using javascript for client side scripting.
0
 
LVL 23

Expert Comment

by:Christopher Kile
Comment Utility
That's because you do not check the return values of your confirm() and, therefore, your application does nothing in response to those values.  Also, you've coded your if statement on the server, not the client, so that in order to execute this code, your button must post back to the server, execute the event handler, then the newly refreshed page displays your confirm() box....then does nothing with the return value because the script you've registered does nothing with the return value.  

You want to run the update based on the response to the confirm() box, so the client code must read the result of the confirm() and then trigger a postback to the server with some condition set that tells the server to go ahead and perform the update.  Do you understand what I've just told you?

0
 

Author Comment

by:acdagirl
Comment Utility
of course I understand it... I know I'm missing something - I would appreciate assistance on *how* to do this...
0
 
LVL 23

Expert Comment

by:Christopher Kile
Comment Utility
*nods* Sorry, I wasn't sure of that based on what you've posted.  Put it down to limited attention span (mine :) )

I'm going to talk about your button as if it was named btnAssign, and as if your Sub btnAssign was called btnAssign_Click.

First, add a hidden input to the form with the id of btnAssignConfirmed. Be sure to verify that the server definition has been created - if not, place a server definition of the hidden input in the page class.

Then, instead of this:

   For i as Integer = 0 to gridD.Rows.Count-1
     Dim cb as CheckBox = CType(gridD.Rows(i).FindControl("Checkbox"), CheckBox)
      If not gridD.Rows(i).Cells(8).Text = " " then
         ClientScript.RegisterStartupScript(Me.GetType(), "", String.Format("confirm('Warning!... Overwrite?');", true)
    end if
'update logic here....


Try this:

If btnAssignConfirmed.Value = "no" Then
    For i as Integer = 0 to gridD.Rows.Count-1
        Dim cb as CheckBox = CType(gridD.Rows(i).FindControl("Checkbox"), CheckBox)
        If not gridD.Rows(i).Cells(8).Text = " " then
            Dim scriptBlock as New StringBuilder("")
           
            scriptBlock.Append("var btnAssign = document.getElementById('btnAssign');")
            scriptBlock.Append("if (btnAssign) {")
            scriptBlock.Append("if (confirm('Warning!... Overwrite?')) {"
            scriptBlock.Append("var el = document.getElementById('btnAssignConfirmed');")
            scriptBlock.Append("el.value = 'yes';
            scriptBlock.Append("document.Form1.submit();")
            scriptBlock.Append("}")
            scriptBlock.Append("}")
            ClientScript.RegisterStartupScript(Me.GetType(), "btnAssign", scriptBlock);
            Exit Function
        End If
    Next
    'If it drops through to here, no confirmation is required.
End If
'update logic here....

0
 

Author Comment

by:acdagirl
Comment Utility
ok, I understand the replacement logic, but I'm having some problems with the hidden input
"First, add a hidden input to the form with the id of btnAssignConfirmed. Be sure to verify that the server definition has been created - if not, place a server definition of the hidden input in the page class."

How does the btnAssign click sub know if btnAssignConfirmed is yes or no?
0
 
LVL 23

Expert Comment

by:Christopher Kile
Comment Utility
>How does the btnAssign click sub know if btnAssignConfirmed is yes or no?

It's initialized to no.  The client sets it to yes if you hit OK from the confirm prompt.  The click sub simply has to check its values.  Does that make sense?
0
 

Author Comment

by:acdagirl
Comment Utility
so this kind of thing:

<input type="hidden" name="btnAssignConfirmed " value="no">
which though your javascript turns into "yes"...

ok, I get it, and will try it, thanks for your help and patience!
0
6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

 
LVL 23

Expert Comment

by:Christopher Kile
Comment Utility
yvw :)
0
 

Author Comment

by:acdagirl
Comment Utility
well it's not working unfortunately. i think there's some problem with the script block and/or my logic... here's the code if you can help:

            For index As Integer = 0 To gridDivision.Rows.Count - 1
      '[...]      
                Dim cb As CheckBox = CType(gridDivision.Rows(index).FindControl("RowLevelCheckBox"), CheckBox)
                If cb.Checked Then
                    If btnAssignConfirmed.Value = "no" Then
                        If Not gridDivision.Rows(index).Cells(8).Text = "&nbsp;" Then
                            Dim scriptBlock As New StringBuilder("")
                            scriptBlock.Append("var btnAssign = document.getElementById('btnAssign');")
                            scriptBlock.Append("if (btnAssign) {")
                            scriptBlock.Append("if (confirm('Warning!... Overwrite?')) {")
                            scriptBlock.Append("var el = document.getElementById('btnAssignConfirmed');")
                            scriptBlock.Append("el.value = 'yes';")
                            scriptBlock.Append("document.form1.submit();")
                            scriptBlock.Append("}")
                            scriptBlock.Append("}")
                            ClientScript.RegisterStartupScript(Me.GetType(), "btnAssign", scriptBlock.ToString())
                            Exit Sub
                        End If
                    End If
                    'update logic ......
               End If
            Next
0
 

Author Comment

by:acdagirl
Comment Utility
p.s. the aspx page contains the
<input id='btnAssignConfirmed' value='no' runat="server" />
and there are no compilation errors.
i just don't get any alert and the line document.form1.submit();") appears on the screen itself...
0
 
LVL 23

Expert Comment

by:Christopher Kile
Comment Utility
Ouch...What's happening is that the script code was not properly formatted into a script tag.  This code should fix that.

Change this:

                            scriptBlock.Append("var btnAssign = document.getElementById('btnAssign');")
                            scriptBlock.Append("if (btnAssign) {")
                            scriptBlock.Append("if (confirm('Warning!... Overwrite?')) {")
                            scriptBlock.Append("var el = document.getElementById('btnAssignConfirmed');")
                            scriptBlock.Append("el.value = 'yes';")
                            scriptBlock.Append("document.form1.submit();")
                            scriptBlock.Append("}")
                            scriptBlock.Append("}")

to this:

                            scriptBlock.Append("<script type='text/javascript'>" & vbCrLf)
                            scriptBlock.Append("<!--" & vbCrLf)
                            scriptBlock.Append("var btnAssign = document.getElementById('btnAssign');")
                            scriptBlock.Append("if (btnAssign) {")
                            scriptBlock.Append("if (confirm('Warning!... Overwrite?')) {")
                            scriptBlock.Append("var el = document.getElementById('btnAssignConfirmed');")
                            scriptBlock.Append("el.value = 'yes';")
                            scriptBlock.Append("document.form1.submit();")
                            scriptBlock.Append("}")
                            scriptBlock.Append("}")
                            scriptBlock.Append(vbCrLf & "//-->")
                            scriptBlock.Append("</script>" & vbCrLf)

0
 

Author Comment

by:acdagirl
Comment Utility
thanks for the fix... it does work, however i have another issue. there's something wrong with the postbacks or something. the first time i access the page and select a row that should trigger the alert, it does, but the update doesn't happen unless I click the assign button again. Also, after that update, the logic no longer works at all... so a row that should trigger the alert simply updates...

here's my screwed up logic... normally I'm not such  ditz but have been working on another project and haven't had any time to devote to really hammering this out, so I'm sorry for the stupidity...

          For index As Integer = 0 To gridDivision.Rows.Count - 1
                uid = gridDivision.DataKeys(index).Value

                Dim cb As CheckBox = CType(gridDivision.Rows(index).FindControl("RowLevelCheckBox"), CheckBox)
                If cb.Checked Then
                    If btnAssignConfirmed.Value = "no" Then
                        If Not gridDivision.Rows(index).Cells(8).Text = "&nbsp;" Then
                            Dim scriptBlock As New StringBuilder("")
                            scriptBlock.Append("<script type='text/javascript'>" & vbCrLf)
                            scriptBlock.Append("<!--" & vbCrLf)
                            scriptBlock.Append("var btnAssign = document.getElementById('btnAssign');")
                            scriptBlock.Append("if (btnAssign) {")
                            scriptBlock.Append("if (confirm('Warning! Reviewer already assigned - Overwrite?')) {")
                            scriptBlock.Append("var el = document.getElementById('btnAssignConfirmed');")
                            scriptBlock.Append("el.value = 'yes';")
                            scriptBlock.Append("document.form1.submit();")
                            scriptBlock.Append("}")
                            scriptBlock.Append("}")
                            scriptBlock.Append(vbCrLf & "//-->")
                            scriptBlock.Append("</script>" & vbCrLf)
                            ClientScript.RegisterStartupScript(Me.GetType(), "btnAssign", scriptBlock.ToString())
                            Exit Sub
                        End If     'end of Cells(8) check
                        'update reviewer: all update commands here - they do work on their own
                    End If        'end of btnAssignConfirmed = "no"
                End If            'end of cb.Checked
            Next                  'iterating through all gridDivision rows

            gridDivision.DataBind()
            lblSummary.Text = "<i>Assign Reviewer</i> update successful."
0
 
LVL 23

Expert Comment

by:Christopher Kile
Comment Utility
Ouch...you are attempting to verify each row is not prefilled then update only that row?  You need to move the update after

End If 'end of btnAssignConfirmed = "no"

Otherwise it will never update after a confirm OK.  
0
 

Author Comment

by:acdagirl
Comment Utility
righto - let me try that... yes, I verify each row is checked, and/or prefilled and update the row. the check being only if it's prefilled to flag with the warning... i have other functionality on the page driven by other buttons so that's why i didn't bundle the Assign button in the gridview, although it would have been alot simpler.
0
 

Author Comment

by:acdagirl
Comment Utility
ok, I did that and added a btnAssignConfirmed = "no" after the update to reset the hidden field so I get the alert prompt for any future page selections. However I still need to manually click the btnAssign after the "ok" for the form to submit my update. Any thoughts on why?
0
 
LVL 23

Accepted Solution

by:
Christopher Kile earned 500 total points
Comment Utility
Hmmmmm....try changing this:

                            scriptBlock.Append("document.form1.submit();")

to this:

                            scriptBlock.Append("__doPostBack('btnAssign, '');")

and if that doesn't work, change it to this:

                            scriptBlock.Append("var evTarg = document.getElementById('__EVENTTARGET');")
                            scriptBlock.Append("if (evTarg) evTarg.value = 'btnAssign';")
                            scriptBlock.Append("document.form1.submit();")

When you have a server-side event handler for a control and you fire that event, and that control has AutoPostBack set to True, then __doPostBack() is called.  This is a Javascript function automatically added to the web page when a control has AutoPostBack set to True and is used to set the hidden variables __EVENTTARGET and __EVENTARGUMENT, the first of which tells the server which control fired the event and the second contains optional information (and is rarely used).  I suspect that when I have you submit the form, it is being submitted in such a way that your button handler is never invoked.  One of these alternate methods should cause the button handler to work.
0
 

Author Comment

by:acdagirl
Comment Utility
wow - the second solution worked! Thank you again for all your help and explanation of the postback stuff... I really appreciate it!
0
 
LVL 23

Expert Comment

by:Christopher Kile
Comment Utility
My pleasure :)
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

This article describes relatively difficult and non-obvious issues that are likely to arise when creating COM class in Visual Studio and deploying it by professional MSI-authoring tools. It is assumed that the reader is already familiar with the cla…
Introduction This article shows how to use the open source plupload control to upload multiple images. The images are resized on the client side before uploading and the upload is done in chunks. Background I had to provide a way for user…
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now