0

I used the following in my MVC3 (aspx) to generate an array from ViewData that contains a list:

<script runat="server">
      void RenderJavascriptHashArray (string listName, string hashName)
            {
            IEnumerable<KeyValuePair<int, string>> pairs = this.ViewData[listName] as IEnumerable<KeyValuePair<int, string>>;

            Response.Write("var " + hashName + " = new Array();\n");
            foreach (KeyValuePair<int, string> pair in pairs)
                {
                Response.Write(hashName + "[" + pair.Key.ToString() + "] = \"" + pair.Value + "\";\n");
                }
            }
</script>

<script>
   <% this.RenderJavascriptHashArray("InfoURLs", "InfoURLs"); %>
</script>

In MVC5 Razor, the array is displayed on the screen because of Response.Write, is there an alternative approach! Would appreciate your suggestions.

hncl
  • 2,295
  • 7
  • 63
  • 129

1 Answers1

0

Try this i do not think you need response if you are in razor.

@Html.Raw(RenderJavascriptHashArray("InfoURLs", "InfoURLs"))
@{
            string RenderJavascriptHashArray (string listName, string hashName)
            {

              IEnumerable<KeyValuePair<int, string>> pairs = this.ViewData[listName] as IEnumerable<KeyValuePair<int, string>>;
                  System.Text.StringBuilder sb = new System.Text.StringBuilder(); 
                  sb.Append("var " + hashName + " = new Array();\n");
               foreach (KeyValuePair<int, string> pair in pairs)
                {
                sb.Append(hashName + "[" + pair.Key.ToString() + "] = \"" + pair.Value + "\";\n");
                }
                return sb.ToString();
            }
}
COLD TOLD
  • 13,513
  • 3
  • 35
  • 52
  • Thank you. Using Html.Raw prints the array on the screen. On debug, I can see the array. However if try to access it from another JavaScript function for example alert(InfoURls[1]) I get InfoURLs is not defined! – hncl Dec 11 '14 at 23:55