DreamTeK
DreamTeK

Reputation: 34177

Passing a string from .NET to a javascript variable

I have tried many ways to pass a string from .net to javascript including .NET serializer, and register startup scripts.

I am looking for the simplest way to populate a javascript variable with a string generated in code behind.

This is what I am currently trying but output is ""

I am open to other suggestions.

VB.NET

Public Property ServerVariable As String

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
  Dim ServerVariable = "'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'"
End Sub

JAVASCRIPT

var data = "<%= ServerVariable %>";
...
List : [data]

DESIRED RESULT

List : ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']

Upvotes: 0

Views: 110

Answers (3)

DreamTeK
DreamTeK

Reputation: 34177

Missing get and set values. Passed variable ServerVariable needs to have a value applied to it.

  Private MyVar As String = ""

  Public Property ServerVariable As String
    Get
      Return MyVar
    End Get
    Set(value As String)
      MyVar = value
    End Set
  End Property

  MyVar = "['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']"

Upvotes: 0

Arindam Nayak
Arindam Nayak

Reputation: 7462

You are doing it correctly, only thing is that you need to do .split(",") in javascript to get desired result.

Like var list = console.log(data.split(","));

Upvotes: 1

invernomuto
invernomuto

Reputation: 10211

This should be a comment, sorry, btw you can access to public props in the aspx;ascx, so this should help

vb.net

Public Property ServerVariable As String

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
  ServerVariable = "['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']"

End Sub

JS

var data = "<%= ServerVariable %>";

Upvotes: 2

Related Questions