locked
How can you use a Javascript object in a Visual Basic function? using ASP.NET/ASMX RRS feed

  • Question

  • User-1312217318 posted

    I have a javascript object called 'layerArr'. This object contains an array of objects. I want to be able to use the values contained in this javascript object in one of my Visual Basic functions.

    Right now I cannot access 'layerArr' from my VB code, how do I send it from the front end (javascript), to the back end(Visual Basic)? I am using ASP.net with ASMX web services

    Initially I thought that it would be possible via WebMethod to retrieve a javascript object from an ajax call. But I've since been told pointless because my VB code is already running server side, not in the client. So if everything that I have done below in not right, how do I achieve what I am requesting?

    the layerArr object I want to be able to use in VB:

    layerArr object

    Here is my Ajax:

        function getAjDataObject(layerArr) {
    
                $.ajax({
                    type: "post",
                    url: "App_Code/DataObjectWebMethod/ChartInfo",
                    async: true,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    processData: false,
                    data: JSON.stringify(layerArr),
                    success: function (data) {
                        result = data;
                    },
                    error: function (a, b, c) {
                        alert("Could not get ChartInfo");
                    }
                });
                return result.d;
            }

    The Web Method:

    Public Class DataObjectWebMethod
    <WebMethod()>
    Public Shared Function ChartInfo(ByVal layerArr As LayerArr) As LayerArr
        Return layerArr
    End Function
    End Class

    And the LayerArr class (not the same as the JSON layerArr object):

    Public Class LayerArr
    Public property AbsoluteEndM As Integer
    Public property AbsoluteStartM As Integer
    Public property EndDate As Date
    Public property EndMetres As Integer
    Public property LayerDate As Date
    Public property LayerDatesFormatted As Date
    Public property Name As String
    Public property Thickness As Integer
    End Class
    Wednesday, May 15, 2019 6:55 PM

All replies

  • User1120430333 posted

    I would think that the ASMX Web method would look kind of what is in the link.

    https://www.aspsnippets.com/Articles/Call-Consume-Web-Service-ASMX-using-jQuery-AJAX-in-ASPNet.aspx

    The Web method would be having a string input parameter I would think of the string Json being passed into the method.

    MethodName(byval json as string) 

    Once you get the serialized Json string in the Web method, then you have to deserialize the Json data into a .NET object. And if it's an array of Json objects, then the .NET object has  to be loaded into a  List<T>.

    An example of a VB method that is calling an ASP.NET WebAPI that is returning an array of Json  DtoProject objects. It gets the Json data, and deserializes the Json array of DTOProject objects in to a .NET DtoProject objects that have been loaded into a List <T>.

    public Function  GetProjsByUserIdApi(userid As String) as List(of DtoProject) Implements IWebApi.GetProjsByUserIdApi
    
                dim dtoprojects = new List(Of DtoProject)
    
                dim url = "http://localhost/WebApiVB/api/project/GetProjectsByUserId?userid=" & userid
    
                Using webclient As New WebClient
                    dim json  = webclient.DownloadString(url)
                    Dim projects = JsonConvert.DeserializeObject(of List(Of DtoProject))(json)
                    dtoprojects = projects
                End Using
    
                Return dtoprojects
    
            End Function
    Public Class DtoProject
    
        Public Property ProjectId As Int32
        Public Property ClientName As String
        Public Property ProjectName As String
        Public Property Technology As String
        Public Property ProjectType As String
        Public Property UserId As String
        Public Property StartDate  As DateTime
        Public Property EndDate As DateTime? 
        Public Property Cost As Decimal
       
    End Class

    Thursday, May 16, 2019 8:18 AM
  • User288213138 posted

    Hi Quektis,
     
    If you javascript object contains an array of object, The parameters of the web method must also be an array.
     
    I made a demo for you as a reference.

    Aspx:
      <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
        <script type="text/javascript" src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
        <script type="text/javascript">
            $(function () {
                $("#btn").on("click", function () {
                    var layerArr = {};
                    var arr = [
                        { name: "layerArr1" },
                          { name: "layerArr2" },
                          {name:"layerArr3"}
                    ];                           
                    $.ajax({
    
                        type: 'POST',
                        url: 'WebForm3.aspx/GetLayerArr',
                        data:JSON.stringify( {layerArr:arr}),
                    contentType: 'application/json; charset=utf-8',
                    dataType: 'json',
                        success: function (r) {
                            console.log(r.d);                                                   
                    }
                });
            });
            })        
        </script>
    
    Aspx.cs:
    <System.Web.Services.WebMethod>
    Public Shared Function GetLayerArr(ByVal layerArr As List(Of LayerArr)) As List(Of LayerArr)
        Return layerArr
    End Function
    
    
    Public Class LayerArr
        Private name As String
    
        Public Property Name As String
            Get
                Return name
            End Get
            Set(ByVal value As String)
                name = value
            End Set
        End Property
    End Class

    The result:

    Best regards,

    Sam

    Thursday, May 16, 2019 8:31 AM
  • User-1312217318 posted

    [DELETED]

    Thursday, May 16, 2019 10:40 AM
  • User753101303 posted

    Same. You STILL have a service that accepts a single layerArr object rather than an array or list that is see the difference ie try :

    layerArr() As LayerArrVb ' an array of objects
    layerArr As LayerArrVb ' a single object

    On the client side it would be data: { 'sectionUID': s, 'XSP': x, 'colour': c, 'layerArr': layerArr} but now it seems this layerArr parameter is not longer passed to your function.

    IMHO avoid chaning your code while others are trying to help. It is often discouraging to try to help someone which changes his code while you try to fix the initial version. And here it seems you don't even tried to take into account the suggested fix in your updated code.

    You told you have an array of objects on the client side and so your VB method must accept an array of objects rather than a single object. Also make sure property names are matching on both sides (not case sensitive). For now I see layerDateformatted on one side but LayerDatesFormatted on the VB side. The other propery names I can check seems fine.

    So try the suggested fix, tell what happens and don't do any change whose purpose is not to make your code work. You'll do that if you want once your CURRENT code works.

    Thursday, May 16, 2019 11:09 AM
  • User-1312217318 posted

    Thanks everyone that was really helpful. It works, but somehow the program is still throwing an error.

    My ajax data field is now: 

    data:JSON.stringify( {layerArr:arr}),

    The program is throwing an error elsewhere in the program where I have the following:

    $scope.removeLayer = function () { var data = { 'layerArr': arr}}

    It is saying that "Type 'WebCE.LayerArrVb' is not supported for deserialization of an array." I tried JSON's serializeArray() function but it doesn't work. Currently trying to figure out how to serialize it as an array

    Tuesday, May 21, 2019 9:14 AM
  • User753101303 posted

    What if you try with what you started with ie JSON.stringify(arr) ? If you expect an array as well on the server side it should work (and it would be what I suggested in my very first post).

    If not I assume you then do an Ajax call and that the message you are showing happens on the server side ???

    Tuesday, May 21, 2019 9:27 AM
  • User-1312217318 posted

    Yes, I have tried using JSON.stringify(arr), if I do that it says "Cannot convert object of type 'System.String' to type 'WebCE.LayerArrVb'". Here is my updated code that is confirmed working (chart info returns the array of objects). I had to create

    convertedLayerArray 

    because there was some incompatible date format:

    Public Class LayerArrVb
        Public Property absoluteEndM As Integer
        Public Property absoluteStartM As Integer
        Public Property endDate As String
        Public Property endMetres As Integer
        Public Property layerDate As String
        Public Property name As String
        Public Property startMetres As Integer
        Public Property thickness As Integer
    End Class


    <WebMethod>
    Public Function ChartInfo(layerArr As List(Of LayerArrVb)) As List(Of LayerArrVb)
    Return layerArr
    End Function
    convertedLayerArray = [];
                for (let i = 0; i < layerArr2.length; ++i) {
                    var convertedEndDate = new Date(parseInt(layerArr2[i].endDate.substr(6)));
                    var convertedEndDate2 = convertedEndDate.getFullYear() + ' ' + (convertedEndDate.getMonth() + 1) + ' ' + convertedEndDate.getDate();
    
                    var convertedLayerDate = new Date(parseInt(layerArr2[i].layerDate.substr(6)));
                    var convertedLayerDate2 = convertedLayerDate.getFullYear() + ' ' + (convertedLayerDate.getMonth() + 1) + ' ' + convertedLayerDate.getDate();
    
                    convertedLayerArray.push({
                        "absoluteEndM": layerArr2[i].absoluteEndM,
                        "absoluteStartM": layerArr2[i].absoluteStartM,
                        "endDate": convertedEndDate2,
                        "endMetres": layerArr2[i].endMetres,
                        "layerDate": convertedLayerDate2,
                        "name": layerArr2[i].name,
                        "startMetres": layerArr2[i].startMetres,
                        "thickness": layerArr2[i].thickness
                    });
                }
                
                $.ajax({
                    type: "POST",
                    url: "WebService.asmx/ChartInfo",
                    async: true,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    data: JSON.stringify({ "layerArr": convertedLayerArray}),
                    success: function (data) {
                        result = data;
                    },
                    error: function (a, b, c) {
                        alert("Ajax call to ChartInfo failed");
                    }
                });



    Tuesday, May 21, 2019 9:47 AM
  • User-1312217318 posted

    Thanks, that didn't work but I hadn't realised that when passing layerArr as a parameter in my code, I have to declare it as a list every time, even though it is already defined as a list. 

    Example: 

    public function AddNewLayer(layerArr As List(Of LayerArrVb))

    It now works 

    Tuesday, May 21, 2019 11:00 AM
  • User753101303 posted

    Great to see it is finally solved. It was suggested in the first two responses before I suggested an array which should work as well :

    ayerArr() As LayerArrVb ' an array of objects
    layerArr As LayerArrVb ' a single object

    I suspect naming your type LayerArr when it is not an array could be perhaps part of the confusion?

    Tuesday, May 21, 2019 11:20 AM