0

I have a question about @helper on Razor. I'm trying do a @helper simple example, but i can´t obtain a result.I need add custom text to javascript code. On firebug i can see that test var is empty, i don´t understand this. This is the code:

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

Thank you very much

2
  • I just added semicolon to the end of the longest row and it works for me. Commented May 22, 2012 at 9:04
  • Thanks Juraj, i saw. But i was not too specific in the trouble. I edit the code in order to see the error Commented May 22, 2012 at 11:02

1 Answer 1

4

If all you want is create a JSON object and assign to a javascript variable then you can check this,

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

Output:

   var testObj = {Id: 1, Text: "hello world"}

UPDATE: If you want to create a JSON array check this,

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

Output:

   var testArray = [{"Id":1,"Text":"hello world"},{"Id":2,"Text":"how are you"}];
Sign up to request clarification or add additional context in comments.

2 Comments

thank you Mark! So the initialization was incorrect. If i wish the following format on array how would be the correct serialization? {array1: {Id: '1',Text: 'hello world'},array2 :{ Id:'2',Text: 'hello world2'}}; Maybe new Dictionary<string,Dictionary<string,object>> ?
Yes, but if you want to create an array of JSON objects check the updated answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.