trying to pass an array variable to java The following is not working, any idea why and how to make it work
Code behind
Public myArray (5) As String
myArray(1) = "A1"
myArray(2) = "A2"
myArray(3) = "A3"
myArray(4) = "A4"
myArray(5) = "A5"
In asp
<button type = "button" onclick="myJava('<%= myArray %>');">Search</button>
In Javascript
function myJava (myArray) {
alert(myArray[1]); // expected answer is A1 but it is not
}
You need to properly encode your array. Firstly, you need to convert it to a JSON string; then you need to encode that string as an HTML attribute value.
Add a reference to the Newtonsoft.Json NuGet package. Add an Imports statement for the Newtonsoft.Json namespace. Add a method to your code-behind to return the properly-encoded function call:
Public Function PassArrayToJavascript(ByVal functionName As String) As String
Dim json As String = JsonConvert.SerializeObject(myArray)
Dim result As String = functionName + "(" + json + ");"
Return System.Web.HttpUtility.HtmlAttributeEncode(result)
End Function
Then update your markup to call this function:
<button type = "button" onclick="<%= PassArrayToJavascript("myFunction") %>">Search</button>