简体   繁体   中英

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

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;
    }

I would appreciate if someone suggests me how to access the list variable from javascript function. Thanks in advanced

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:

在此处输入图像描述

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).

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