从ViewBag填充javascript变量?

时间:2015-01-19 16:49:24

标签: javascript asp.net asp.net-mvc json viewbag

我在stackoverflow上看到我们可以用ViewBags(用razor)填充js变量:

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

用这个:

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

我想用aspx而不是razor做同样的事情。你能救我吗?

2 个答案:

答案 0 :(得分:1)

在我的控制器中:

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

在我的aspx中:

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

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

结果:谢谢你,它有效!

答案 1 :(得分:0)

public 属性添加到您的页面并在页面加载上填充(您可能必须在Page Init上执行此操作,我无法先记住哪些进程)。

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
}

标记:

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

请注意,我使用UserToSerialize来避免干扰Page.User property