Link to home
Start Free TrialLog in
Avatar of thamilto0410
thamilto0410

asked on

How to call a codebehind procedure from javascript

I am new to vb.net.  I am on a deadline therefore I cannot use .net validators.  I am using prebuilt and functioning javascript validation.  I am using the registerclientscriptblock in my codebehind function attached to a button to call the javascript validation and it works perfect.  Once the validation is done I would like to return to the procedure hide one panel and show the other panel that is a review of the form data.  My question is how do I do this from javascript?  If I place the functionality for the panels below the call to the javascript validation function the codebehind does not even halt if the elements are not populated with values it just goes right to the review panel.  My current code is below.


Public Sub close_Onclick(ByVal Src As Object, ByVal E As EventArgs)
        Dim theValue As String
        If Session("role") = "Pl Specialist" Or Session("role") = "Ast Team Captain" Then
            theValue = "validateCU_PS('" & Session("team") & "');"
        Else
            theValue = "validateCU_TC('" & Session("team") & "');"
        End If
        'MsgBox(theValue)
        Dim sb As New StringBuilder()
        sb.Append("<script language=javascript>")
        sb.Append(theValue)
        sb.Append("</script>")
        ClientScript.RegisterStartupScript(Me.GetType(), "validate", sb.ToString())
       
       
            EvalForm.Visible = False
            Dim displayValues1 As New StringBuilder()
            Dim displayValues2 As New StringBuilder()
            Dim thecols As String = ""
            Dim thevals As String = ""
            Dim postedValues As NameValueCollection = Request.Form
            Dim nextkey As String = ""
            For i As Integer = 0 To postedValues.AllKeys.Length - 1
                nextkey = postedValues.AllKeys(i)
                If nextkey.Substring(0, 2) <> "__" Then
                    If nextkey <> "senditback" And nextkey <> "closecase" And nextkey <> "sbmtForm" Then
                        If postedValues(i) <> "Select" And postedValues(i) <> "Select One" Then
                            displayValues1.Append(nextkey)
                            displayValues1.Append("<br>")
                            If postedValues(i).ToString = "" Then
                                displayValues2.Append("NULL")
                            Else
                                displayValues2.Append(postedValues(i))
                            End If
                            displayValues2.Append("<br>")
                        End If
                    End If
                End If

            Next
            Session("evalcolumns") = Left(Trim(displayValues1.ToString), Len(displayValues1.ToString) - 1)
            Session("evalvalues") = Left(Trim(displayValues2.ToString), Len(displayValues2.ToString) - 1)
            thecolumns.Text = displayValues1.ToString()
            thevalues.Text = displayValues2.ToString()
            ReviewEval.Visible = True
       
    End Sub
ASKER CERTIFIED SOLUTION
Avatar of Bob Learned
Bob Learned
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
you can use clientcallback feature in asp.net 2.0. ICallBackEventHAndler is the main interface to be used, here is an example:-

http://onthefencedevelopment.com/?p=149

with this technique you need not to go for AJAX.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of thamilto0410
thamilto0410

ASKER

Thank you all.  Let me finish taking down my tree and then I will investigate the links and get back to you if I need help.  You guys are AWESOME and this site is worth the monthly subscription.   HAPPY NEW YEAR to each of you!!
thelearnedone---Ajax is great but might be overkill and I am not certain I can get IT to install the dll on server so for now I would like to try the clientcallback.
buggycoder---Your idea I think is the way for me.  I looked at the link to the onthefencedevelopment article but can't quite figure out how to implement for my situation could you assist with an example of calling the javascript and then calling a codebehind function that will set one one panel to visible and the other to hidden please?  Either that or maybe send me some more examples and hopefully I will come across one that will be close enough that I can apply it to my needs.  Thanks.
buggycoder:  I went through the example but still don't understand.  In the example above there are 2 javascript functions and it appears onclick fires one of them and the codebehind is then called with the UseCallBack which then calls the other javascript and it populates an element.  I need to call a javascript validation function with a click event and then call the codebehind from the javascript validation that then calls a procedure in the code behind that hides one panel and shows another panel.  Truly I am not trying to be difficult just so new to .net that I can't quite grasp.  I will continue to search the web for additional examples.
buggycoder:  I think I am headed in the right direction can you look over the below code and provide feedback on any problems you see?  I am just beginning to understand and don't know if my syntax is correct.  I can't test it until I get back to work on Monday as I need to build one more table for my home oracle db and the data and structure are at work.

This is my client side validation stored in my js file
function validate_TC()
{
 
 var theName;
 var theDate;      
          
 for (j=0; j < document.case_eval.elements.length; j++)

  //alert(document.case_eval.elements[j].type + "=" + document.case_eval.elements[j].name);
  if (document.case_eval.elements[j].type == 'text')
  {
     eval('document.case_eval.elements[j].style.backgroundColor=otherColor');
     theName = document.case_eval.elements[j].name;
    if (theName == "date_received" || theName == "date_assigned") {      
    theDate = document.getElementById(theName);    
    if (theDate.value.length > 0 && theDate.value != "N/A") {      
    if(isDate(theDate.value)==false) {
       eval('document.case_eval.elements[j].style.backgroundColor=theColor');
       theDate.focus();
       return false;  
           }
   }
   }
   if (document.case_eval.elements[j].value == "") {
        alert(document.case_eval.elements[j].name + " cannot be blank. Please correct.");            
        eval('document.case_eval.elements[j].style.backgroundColor=theColor');
        document.case_eval.elements[j].focus();
        return false;
         }
        }
        CallServer();
return true;

}

function ReceiveServerData(retValue) {
    document.getElementById("Results").innerHTML = retValue;
}

In my codebehind I am using attributes add with onclick for the javascript validation  and then I have this above the page load:

 Implements System.Web.UI.ICallbackEventHandler
    Protected returnValue As String

    Public Sub RaiseCallbackEvent(ByVal eventArgument As String) _
    Implements System.Web.UI.ICallbackEventHandler.RaiseCallbackEvent

        EvalForm.Visible = False
        Dim displayValues1 As New StringBuilder()
        Dim displayValues2 As New StringBuilder()
        Dim thecols As String = ""
        Dim thevals As String = ""
        Dim postedValues As NameValueCollection = Request.Form
        Dim nextkey As String = ""
        For i As Integer = 0 To postedValues.AllKeys.Length - 1
            nextkey = postedValues.AllKeys(i)
            If nextkey.Substring(0, 2) <> "__" Then
                If nextkey <> "senditback" And nextkey <> "closecase" And nextkey <> "sbmtForm" Then
                    If postedValues(i) <> "Select" And postedValues(i) <> "Select One" Then
                        displayValues1.Append(nextkey)
                        displayValues1.Append("<br>")
                        If postedValues(i).ToString = "" Then
                            displayValues2.Append("NULL")
                        Else
                            displayValues2.Append(postedValues(i))
                        End If
                        displayValues2.Append("<br>")
                    End If
                End If
            End If

        Next
        Session("evalcolumns") = Left(Trim(displayValues1.ToString), Len(displayValues1.ToString) - 1)
        Session("evalvalues") = Left(Trim(displayValues2.ToString), Len(displayValues2.ToString) - 1)
        thecolumns.Text = displayValues1.ToString()
        thevalues.Text = displayValues2.ToString()
        ReviewEval.Visible = True
        returnValue = "What are you doing?"
    End Sub

    Public Function GetCallbackResult() As String Implements _
        System.Web.UI.ICallbackEventHandler.GetCallbackResult
        Return (returnValue)
    End Function

AND this in the page load

 Dim cbReference As [String] = Page.ClientScript.GetCallbackEventReference(Me, "arg", "ReceiveServerData", "context")
            Dim callbackScript As [String]
            callbackScript = "function CallServer(arg, context)" & "{ " & cbReference & ";}"
            Page.ClientScript.RegisterClientScriptBlock(Me.[GetType](), "CallServer", callbackScript, True)

WILL IT WORK?
call back part looks good. it is implemented as required....
hope you get your resolution soon

happy programming....
**Buggy
:-)
buggycoder:  Need help.  Back at work.  Incorporated the above into the files here and javascript runs fine but when it hits the CallServer() portion which I believed to be part of the callback it states object expected.  What am I doing wrong?
buggycoder: never mind I figured out that I was not passing arguments in the call to CallServer and need to.  But now it fires through but does not fire the part that hides one panel and shows the next and I have another problem.  Now that I have built the callback in if any of the validation elements are empty it is suppose to set focus to that element and return false and it fires right past the change of the background color and the focus and seems as if it is reloading the form and I did not want that can you assist?
buggycoder:  Figured out the javascript and that is working as it should be but the callback does not fire at all any ideas as to why?
Okay this is to all you guys that have been assisting me.  I am trying to resolve this but due to my ignorance with .net (I have only been working in this environment for 6 weeks)  I am obviously trying something that is not possible.  I just found this line in a callback article ::  The Client Callback feature allows you execute code from a web form without posting the form back to the server.   If this is so then I definitely cannot use the stringbuilder object and request.form values to populate the stringbuilder and then set the stringbuilders values to labels in a hidden panel which is then supposed to get set to visible  and the current panel to hidden.  Having said that how can I achieve what I need to do?  Is ajax the way to go or is that not doable either and I should just be passing all of this to another pages.  Please help.
So noone can offer any additional asistance?
I figured it out myself using  __doPostback() after my validation.
I awarded points because each expert tried to assist with their remarks.  I graded as C because I found the solution myself.