Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/393.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么在使用C#JavaScriptSerializer和RegisterClientScriptBlock时JSON标签无效?_C#_Javascript_Asp.net_Json_Serialization - Fatal编程技术网

为什么在使用C#JavaScriptSerializer和RegisterClientScriptBlock时JSON标签无效?

为什么在使用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

我尝试向客户端脚本公开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在生成的脚本的第三行显示“无效标签”错误:

<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。我一开始不理解区别。谢谢