0

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

どうもありがとうございます

4

1 に答える 1

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"}];
于 2012-05-22T13:58:08.547 に答える