我对Razor上的@helper有疑问。我正在尝试做一个@helper简单示例,但我无法获得结果。我需要将自定义文本添加到javascript代码中。在firebug上我可以看到test var是空的,我不明白这一点。这是代码:
@fillString()
@renderScript()
@helper fillString(){
test = new List<string>() ;
test.Add("Id : '1'");
test.Add("Text: 'hello world'");
}
@helper renderScript(){
<script type="text/javascript">
var count = "{ @Html.Raw(test.Count) }";
var testArray = @{ new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(test.ToArray()); };
</script>
}
非常感谢
答案 0 :(得分:4)
如果你想要的只是创建一个JSON对象并分配给一个javascript变量,那么你可以检查一下,
@helper renderScript()
{
var test = new Dictionary<string, object>();
test.Add("Id", 1);
test.Add("Text", "hello world");
var json = @Html.Raw(new JavaScriptSerializer().Serialize(test));
<script type="text/javascript">
var testObj = @json;
</script>
}
输出
var testObj = {Id: 1, Text: "hello world"}
更新:如果要创建JSON数组,请检查此内容,
var test = new Dictionary<string, object>();
test.Add("Id", 1);
test.Add("Text", "hello world");
var test1 = new Dictionary<string, object>();
test1.Add("Id", 2);
test1.Add("Text", "how are you");
var json = @Html.Raw(new
System.Web.Script.Serialization.JavaScriptSerializer()
.Serialize(new[]{test, test1}));
<强>输出:强>
var testArray = [{"Id":1,"Text":"hello world"},{"Id":2,"Text":"how are you"}];