2

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?

3
  • '@Html.Raw(userInfoJson)' ---> '<%=userInfoJson%>' Commented Jan 19, 2015 at 16:52
  • 2
    You don't need JSON.parse Commented Jan 19, 2015 at 17:45
  • 1
    @userfloflo Are you asking for ASP.Net Web Form or ASPX View Engine? Commented Jan 19, 2015 at 19:33

2 Answers 2

1

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!

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.