Home > Blockchain >  How to call a list declared in VB.net from aspx
How to call a list declared in VB.net from aspx

Time:09-06

I'm trying to build a website ASP.net with vb.net. And I'm trying to access the declared list in VB.net from ASPX page using java script but unfortunately I can't.

Here is my back end code

  Protected CustomerRoleTypes As New List(Of CustomerRoleType)
  CustomerRoleTypes.Add("Junior")

     function ValidateRoleType() {
        const customerRoleTypes = "<%: string.Concat(",",CustomerRoleTypes )%>"; // not getting any values here
        const restrictedCustomerRoles = customerRoleTypes.split(",");
        
        return true;
    }

How can I access the list variable from javascript function?

CodePudding user response:

In most cases, you should consider setting up a web method, and then doing a ajax call from client js code. That is the "normal" way of doing such things.

However, you can certainly use a client side "server" expression as your sample attempts.

Your code behind on the web page?

Well, I don't know, see, nor have your class and the list.

But, you can do it this way:

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

End Sub

Public Function MyFriendList() As String


    Dim MyCoolFriends As New List(Of Person)

    ' add two people to the cool friends list

    Dim OnePerson As New Person

    OnePerson.FirstName = "Clark"
    OnePerson.LastName = "Kent"
    MyCoolFriends.Add(OnePerson)

    OnePerson = New Person
    OnePerson.FirstName = "Bruce"
    OnePerson.LastName = "Wayne"
    MyCoolFriends.Add(OnePerson)

    Dim sResult = JsonConvert.SerializeObject(MyCoolFriends)

    Return sResult


End Function

Class Person
    Public FirstName As String
    Public LastName As String
End Class

So, you can then return that "list" of people (or in your case role types).

Then in your markup, you can use the expression like you have, say this:

Lets for testing just drop in a button we click, and show the first person in our list.

        <asp:Button ID="cmdShow" runat="server" Text="Show cool friends"
            OnClientClick="ShowFriendsTest();return false"  />

        <script>

            function ShowFriendsTest() {

                MyFriendsRaw = '<%= MyFriendList() %>'
                MyFriends = JSON.parse(MyFriendsRaw)
                // show first person in list
                OnePerson = MyFriends[0]
                alert(OnePerson.FirstName   ' '   OnePerson.LastName)                    
            }

        </script>

When we run the above, we see this:

enter image description here

The above assumes you using some kind of serializer.

I am using newtonsoft's json (you can use nuget to install if you don't have).

  • Related