Search code examples
javascriptjqueryasp.netvb.netwebmethod

How do I call a server side VB.net function from jquery in an asp.net form?


I am trying to call a method in my server-side vb code from jquery.

    import System.Web.Services
    ...
    'my VB.net Code
    <WebMethod()> _
    Public Shared Function SubmitReport_Click()
        'this is where my code will go
        Return Nothing
    End Function

In my javascript code the alert is being called but the SubmitReport_Click is not being called.

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager>

<script type="text/javascript">
    $("#<%= FileInput.ClientID%>").on('filebatchselected', function (event) {
        alert("file input");
        pagemethods.SubmitReport_Click();
    })
</script>

Solution

  • I'd make a function that fires on the click event and calls over to your web method using AJAX, and use JSON to pass any relevant data.

    $(".clickMe").click(doWebMethod);
    
    function doWebMethod () {    
        var data = { 'name': 'jessikwa' , 'location': 'ny' }
        var params = "{'dataPackage': '" + JSON.stringify(data) + "'}";
        $.ajax({
            type: "POST",
            url: webMethodUrl,
            async: true,
            data: params,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                alert(msg.d);
            },
            error: function () {
                alert("fail");
            }
        });
    }
    
    //VB HERE
    
    <WebMethod()> _
    Public Shared Function SubmitReport_Click(ByVal dataPackage as String) as String
        Dim rtnStr As String = "OK"
        //deserialize data package here
        Return rtnStr
    End Function