【问题标题】:ASP.NET MVC Razor Rendering script javascriptASP.NET MVC Razor 渲染脚本 javascript
【发布时间】:2012-05-28 16:59:31
【问题描述】:

我对 Razor 上的 @helper 有疑问。我正在尝试做一个@helper 简单示例,但我无法获得结果。我需要将自定义文本添加到 javascript 代码中。在萤火虫上我可以看到测试变量是空的,我不明白这一点。这是代码:

@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>
}

非常感谢

【问题讨论】:

  • 我刚刚在最长行的末尾添加了分号,它对我有用。
  • 谢谢 Juraj,我看到了。但我对麻烦并不太具体。我编辑代码以查看错误

标签: javascript asp.net-mvc razor helper


【解决方案1】:

如果您只想创建一个 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"}];

【讨论】:

  • 谢谢你,马克!所以初始化不正确。如果我希望数组上有以下格式,那么正确的序列化如何? {array1:{Id:'1',Text:'hello world'},array2:{Id:'2',Text:'hello world2'}};也许新 Dictionary> ?
  • 是的,但是如果您想创建 JSON 对象数组,请检查更新后的答案。
猜你喜欢
  • 2011-05-03
  • 2013-05-12
  • 1970-01-01
  • 2014-12-13
  • 1970-01-01
  • 1970-01-01
  • 2019-08-26
  • 2015-02-02
  • 2015-04-13
相关资源
最近更新 更多