flofreelance
flofreelance

Reputation: 944

Populate javascript variable from ViewBag?

I saw on stackoverflow we can do this to populate js variables with ViewBags (with razor):

@{
    var jss = new System.Web.Script.Serialization.JavaScriptSerializer();
    var userInfoJson = jss.Serialize(ViewBag.User);
 }

with this:

<script>
 //use Json.parse to convert string to Json
  var userInfo = JSON.parse('@Html.Raw(userInfoJson)');
</script>

I want to do the same thing with aspx not razor. Can you help me?

Upvotes: 2

Views: 748

Answers (2)

flofreelance
flofreelance

Reputation: 944

In my controller:

Viewbag.test="Thanks to you it works!"

  In my aspx:

public String test {get; set;}
protected void Page_Load(object sender, EventArgs e)
{
  test = ViewBag.test; 
}

<script>
  alert('<%=test%>');
</script>

Result: Thanks to you it works!

Upvotes: 1

mason
mason

Reputation: 32694

Add a public property to your page and populate it on Page Load (you may have to do it on Page Init, I can't remember which processes first).

public UserType UserToSerialize {get; set;}

protected void Page_Load(object sender, EventArgs e)
{
    UserToSerialize = LoadUser(); //I assume you've got some magic to do this already
}

Markup:

<script>
  var userInfo = JSON.parse("<%# new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(UserToSerialize) %>");
</script>

Notice I use UserToSerialize to avoid interfering with the Page.User property.

Upvotes: 0

Related Questions