简体   繁体   中英

call a vb.net subrouting from a javascript function?

hi folks i have a subroutine called CheckDate() in the code behind.

How would I call that subroutine from a javascript function?

Cheers,

-Jonesy

You can't call it directly as function call. because Javascript is a scripting langauge aimed for web browsers.

you may use AJAX or full page post sending the parameters to allow you to execute the subroutine.

Read more about Ajax it is the better way to go.

To expand on what Kronass said there I've found this article to be useful in the past for doing what you want http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/ . Encosia also has a heap of other blog plots on this if you do a bit of searching

What you're looking to use is normally called a WebMethod, ScriptMethod or Page Method depending on which framework you're using

One way to do this is by using the ICallbackEventHandler interface. I saw you had a question regarding the AjaxControToolkit CalendarExtender the other day so I'm guessing this question is in relation to that and how you do some validation in a server-side method. ICallbackEventHandler is AJAX, but you can write your validation as a normal method, not a PageMethod/WebMethod. It's slightly more fiddly on the Javascript side, but not by much.

Let's start with our basic textbox and calendar extender:

<form id="form1" runat="server">
<asp:ScriptManager runat="server" ID="ScriptManager" />
<div>
<asp:TextBox runat="server" ID="DateTextBox" />
<ajaxtoolkit:CalendarExtender runat="server" ID="CalendarExtender" TargetControlID="DateTextBox" 
PopupButtonID="SelectorButton" OnClientDateSelectionChanged="checkDate" Format="dd MMM yyyy" /> 
<asp:ImageButton runat="server" ID="SelectorButton" ImageUrl="Path to a pretty graphic" />
<br />
<asp:Label runat="server" ID="ValidDateLabel" />
</div>
</form>

I've added the OnDateSelectionChanged attribute of the extender as this will kick off the process of calling the server-side method; we'll come back to what goes in there shortly.

In the class declaration in your code-behind, you need to say that you are implementing the interface:

Partial Public Class _Default
    Inherits System.Web.UI.Page
    Implements ICallbackEventHandler

To implement the interface we then need to add two more methods to handle the two methods in the interface, RaiseCallbackEvent and GetCallbackResult. We also need a property for a bit of temporary storage of the date we are trying to validate.

Private mCallbackDate As Date

Private Property CallbackDate() As Date
    Get
        Return mCallbackDate
    End Get
    Set(ByVal value As Date)
        mCallbackDate = value
    End Set
End Property

Public Sub RaiseCallbackEvent(ByVal eventArgument As String) Implements ICallbackEventHandler.RaiseCallbackEvent
    'eventArgument will contain the date the user selected from the extender

    Dim testDate As Date

    If eventArgument = String.Empty Then
    Else
        If Date.TryParse(eventArgument, testDate) Then
            'If we have a legal date selected then store it
            Me.CallbackDate = testDate
        End If
    End If

End Sub

Public Function GetCallbackResult() As String Implements ICallbackEventHandler.GetCallbackResult

    Dim result As String = String.Empty

    'Get the date that we stored in memory and pass it to our CheckDate function
    'We'll pass back to the Javascript in the page the string 'true' if the date is
    'valid under our business rules and 'false' if it isn't
    If checkDate(Me.CallbackDate) Then
        Return "true"
    Else
        Return "false"
    End If

End Function

Public Function checkDate(ByVal dateToCheck As Date) As Boolean

    'If the date is in the future then return True, otherwise False
    If dateToCheck > Date.Today Then
        Return True
    Else
        Return False
    End If

End Function

There's one more bit of server-side we need to add, in Page_Load, which does the hooking up of the Javascript and server-side code. The ClientScriptManager's GetCallbackEventReference function will inject a bit of script into our page that takes care of the communication between browser and server. Then we just need to register a script block that calls the injected script - we'll call this function checkDateOnServer.

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    Dim callbackScript As String

    callbackScript = "function checkDateOnServer(arg){" & _
        Page.ClientScript.GetCallbackEventReference(Me, "arg", "receiveDateValidation", "") & _
        "}"

    ClientScript.RegisterClientScriptBlock(Me.GetType, "callback", callbackScript, True)

End Sub

Back to the client-side bits. We need to write a Javascript checkDate function that'll pass the user's selected date into the callback.

    function checkDate()
    {
        // Get the date the user selected
        var selectedDate = document.getElementById('DateTextBox').value; 

        // This will start the callback sequence
        checkDateOnServer(selectedDate);
    }

The last bit we need to do is receive the value coming back from the server, which we said in Page_Load would be called receiveDateValidation.

    function receiveDateValidation(arg, context)
    {
        var ValidDateLabel = document.getElementById('SelectedDateLabel');

        // We get a string value back from the server which is 'true' or 'false'        
        if (arg == 'true')
        {
            ValidDateLabel.innerText = 'Your date IS valid';
        }
        else
        {
            ValidDateLabel.innerText = 'Your date IS NOT valid';
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM