在客户端函数(Javascript)中调用服务器端方法

Calling Serverside method within Client Side Function (Javascript)

本文关键字:调用 服务器端 方法 Javascript 客户端 函数      更新时间:2023-09-26

有人能帮助我在javascript函数中调用VB.NET方法吗?我的方法不是共享/静态的,也不返回任何内容。它只是简单地将数据保存到数据库并重定向用户。请帮帮我,这是我的代码:

VB方法

  Public Function SaveVehicles()
          Dim res As Boolean
             If res = True Then
            Dim sModel As String = cboModel.SelectedValue
            Dim sVariant As String = cboVariant.SelectedValue
            Dim sColor As String = cboColor.SelectedValue
            cboModel.SelectedValue = sModel
            cboVariant.SelectedValue = sVariant
            cboColor.SelectedValue = sColor

            Dim oData As New WebServVehSwapping
            Dim strSql As String
            Dim sDealer As String
            Dim sUserName As String
            'sDealer = "TBP01"
            sDealer = Trim(Request.QueryString("dealercode"))
            If sDealer = "" Then sDealer = "TBP01"
            sUserName = "User1"
            '------------------------------------------
            strSql = oData.InsertTblRequirement( _
              sDealer _
             , Now.ToString _
             , sUserName _
             , cboColor.Text.Trim _
             , cboModel.Text.Trim _
             , cboVariant.Text.Trim, "Open")
            MsgBox("OKAY")
            Response.Redirect("MyRequirements.aspx?DealerCode=" & sDealer)
        Else
            'do Nothing
        End If
    End Function

这是我的Javascript函数

   function ConfirmView()
    {   
        var Ok = confirm('There is/are existing vehicle(s) in Network Vehiches for sale, View Vehicle(s)?');
        if(Ok==true)
        {
       location.href = 'NetworkVehiclesforSale.aspx';
        return false;
        }
        else if (Ok!=true)
        {
         //THE VB METHOD GOES HERE     
      }
}

我试过回调处理程序,它只适用于返回something/string 的函数

我也尝试过Pagemethod,但它只适用于静态/共享函数。请帮帮我,我真的非常需要它。PLEasee。感谢

。Net web服务不能发挥神奇的作用,也就是说,你不能在服务器上对Ajax请求发出重定向响应,并期望整个页面都被重定向。唯一会发生的事情是Ajax调用被重定向到另一个页面,并试图从那里获取数据。如果要在客户端浏览器中更改页面,则必须在客户端通过JavaScript(例如document.location = url_returned_by_your_function_through_ajax_call)进行更改。

您可能想阅读"构建Windows Communication Foundation Services简介"-http://msdn.microsoft.com/en-us/library/aa480190.aspx

特别是:"使用WCF 3.5设计和构建RESTful Web服务指南"-http://msdn.microsoft.com/en-us/library/dd203052.aspx

还可以查看一些javascript库,这些库使调用RESTful web服务变得简单,比如jQuery-http://www.jquery.com/

使用jQuery,您可以调用服务器端的VB.NET代码,如下所示:

$.ajax({  
    type: "GET",  
    contentType: 'text/json',  
    dataType: 'json',  
    url: "https://URL-TO-SERVICE-HERE/...",  
    timeout: 10000,  
    error: function () {  
        // Deal with the error  
    },  
    success: function (data) {  
        // Do something with the result
        // Example:
        if (data.dealerCode) 
            location.href = 'MyRequirements.aspx?DealerCode=' + data.dealerCode;

    }  
});