我正在嘗試用 vb.net 建立一個網站 ASP.net。我正在嘗試使用 java 腳本從 ASPX 頁面訪問 VB.net 中宣告的串列,但不幸的是我不能。
這是我的后端代碼
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;
}
如果有人建議我如何從 javascript 函式訪問串列變數,我將不勝感激。先謝謝了
uj5u.com熱心網友回復:
在大多數情況下,您應該考慮設定一個 Web 方法,然后從客戶端 js 代碼進行 ajax 呼叫。這是做這些事情的“正常”方式。
但是,您當然可以使用客戶端“服務器”運算式作為示例嘗試。
你的代碼在網頁后面?
嗯,我不知道,看,也沒有你的班級和名單。
但是,你可以這樣做:
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
因此,您可以回傳該人員“串列”(或在您的情況下為角色型別)。
然后在你的標記中,你可以像你一樣使用運算式,這樣說:
讓我們只需單擊一個按鈕進行測驗,然后顯示我們串列中的第一個人。
<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>
當我們運行上面的代碼時,我們會看到:
以上假設您使用某種序列化程式。
我正在使用newtonsoft的json(如果沒有,可以使用nuget安裝)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/503724.html
標籤:javascript C# 网 。网 VB.net
上一篇:如何在VisualBasic中執行與awaitawait等效的C#
下一篇:如何在閱讀后從txt中洗掉一行