[英]Passing Dictionary from controller to Javascript
我有一个这样的视图模型:
public class weightdata
{
...some properties
public string weights;
}
然后,我在控制器中:
weightdata details = new weightdata();
Dictionary<string,float> dict = new Dictionary<string,float>();
//do something to fill the dictionary with values
var ser = new System.Web.Script.Serialization.JavaScriptSerializer();
details.weights = ser.Serialize(dict);
return View(details);
然后在视图中:
<script type="text/javascript">
var dict = @{Html.Raw(new JavaScriptSerializer().Deserialize<Dictionary<string,float>>(Model.Weights));}
</script>
但是页面的呈现方式是:var dict =(空白)
如何将这个值字典放入javascript可以使用的位置?
您的媒体资源已经序列化,这意味着它已经是JSON。 您不想在视图上反序列化,只需直接将其写出即可:
var dict = @Html.Raw(Model.Weights);
另一种选择是将属性设置为Dictionary<string, float>
而不是字符串,然后在视图上对其进行序列化:
var dict = @Html.Raw(new JavaScriptSerializer().Serialize(Model.Weights));
我最近阅读的内容可能会使您的观点更清晰-您实际上可以使用type="application/json"
将JSON转储到其自己的script
标签中,并在javascript中进行引用。 这可能会使您的编辑器更快乐,因为将javascript与C#代码分开更容易。
就像是:
<!-- assuming your Weights property is the serialized JSON string -->
<script id="some-json" type="application/json">
@Model.Weights
</script>
<script type="text/javascript">
var dict = JSON.parse(document.getElementById("some-json").innerHTML);
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.