簡體   English   中英

ASP.NET MVC Razor渲染腳本javascript

[英]ASP.NET MVC Razor Rendering script javascript

我對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"}];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM