为什么在使用C#JavaScriptSerializer和RegisterClientScriptBlock时JSON标签无效?
我尝试向客户端脚本公开ASP.NET web表单中的匿名类型:为什么在使用C#JavaScriptSerializer和RegisterClientScriptBlock时JSON标签无效?,c#,javascript,asp.net,json,serialization,C#,Javascript,Asp.net,Json,Serialization,我尝试向客户端脚本公开ASP.NET web表单中的匿名类型: var thing = new { red = other.Red, green = other.Green, blue = other.Blue, }; JavaScriptSerializer serializer = new JavaScriptSerializer(); Page.ClientScript.RegisterClientScriptBlock(thing.GetType(), "Thi
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在生成的脚本的第三行显示“无效标签”错误:
<script type="text/javascript">
//<![CDATA[
{"red":null,"green":null,"blue":null}//]]>
</script>
//
我觉得双引号是个问题,但我不明白为什么。我看了一下,这似乎是正确的。我做错了什么?您必须将该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);
忘记添加了,它是有效的JSON,只是不是有效的JavaScript。我一开始不理解区别。谢谢