我有关于 Razor 上的 @helper 的问题。我正在尝试做一个 @helper 简单示例,但我无法获得结果。我需要将自定义文本添加到 javascript 代码中。在 Firebug 上我可以看到测试变量是空的,我不明白这一点。这是代码:
@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>
}
非常感谢
最佳答案
如果您想要的只是创建一个 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"}];
关于javascript - ASP.NET MVC Razor 渲染脚本 javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10698032/