ASP.NET MVC Razor 渲染脚本 JavaScript

ASP.NET MVC Razor Rendering script javascript

本文关键字:脚本 JavaScript Razor NET MVC ASP      更新时间:2023-09-26

我有一个关于 Razor @helper的问题。我正在尝试做一个@helper简单的例子,但我无法获得结果。我需要将自定义文本添加到 JavaScript 代码中。在火虫上,我可以看到测试 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>
}

谢谢

如果你想要的只是一个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"}];