为什么JSON标签无效时使用c# JavaScriptSerializer和RegisterClientScriptBl
本文关键字:JavaScriptSerializer RegisterClientScriptBl JSON 标签 无效 为什么 | 更新日期: 2023-09-27 18:18:18
我在ASP中有一个匿名类型。. NET web表单,我试图暴露给客户端脚本:
var thing = new
{
red = other.Red,
green = other.Green,
blue = other.Blue,
};
JavaScriptSerializer serializer = new JavaScriptSerializer();
Page.ClientScript.RegisterClientScriptBlock(thing.GetType(), "Thing", serializer.Serialize(thing), true);
Firebug在生成的脚本的第三行显示了一个"invalid label"错误:
<script type="text/javascript">
//<![CDATA[
{"red":null,"green":null,"blue":null}//]]>
</script>
我觉得双引号是问题所在,但我不明白为什么。我看了JSON.org上的示例页面,看起来应该是有效的。我做错了什么?
您必须将该JSON对象设置为变量或将其作为函数参数传递,示例如下:
var thing = new
{
red = other.Red,
green = other.Green,
blue = other.Blue,
};
JavaScriptSerializer serializer = new JavaScriptSerializer();
string js = String.Format("var jsonObject= {0}; alert({0})", serializer.Serialize(thing));
Page.ClientScript.RegisterClientScriptBlock(thing.GetType(), "Thing", js , true);