简体   繁体   中英

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']

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 %>";

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(","));

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']"

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