Convert an array of C # strings to a Javascript array

I am passing an array of C # strings to a method that uses TagBuilder to create some Javascript. It seems I cannot get the actual elements in an array in my Javascript:

public static IHtmlString NewsTicker(this HtmlHelper htmlHelper, string[] arrTickerContents) { TagBuilder script = new TagBuilder("script"); script.Attributes.Add("type", "text/javascript"); script.InnerHtml = @" var rss_scr_contents = new Array(); $.each('" + arrTickerContents + @"', function (i, objValue) { rss_scr_contents[i] = objValue; }); return MvcHtmlString.Create(script.ToString()); } 

This leads to the following source code:

 var rss_scr_contents = new Array(); $.each('System.String[]', function (i, objValue) { rss_scr_contents[i] = objValue; }); 

What is the correct syntax for this?

+4
source share
3 answers

The problem is that arrTickerCountents.ToString() does not return the expected results.

For example, (new [] {"hello", "world"}).ToString() evaluates to "System.String[]" , which is not useful here.

A valid way to handle this is to use a converter, which can emit a valid JavaScript value from a suitable .NET object - the most common tool is probably a JSON converter. I like Json.NET , but this should work with other converters.

 var jsonArray = JsonConvert.SerializeObject(arrTickerContents); script.InnerHtml = @" var rss_scr_contents = []; $.each(" + jsonArray + @", function (i, objValue) { rss_scr_contents[i] = objValue; }) "; // Please make sure to post valid code 

Since the above loop does not process, it considers a simpler alternative. (I prefer not to use var with global window properties.)

 script.InnerHtml = @"rss_scr_contents = " + jsonArray + ";"; 

I recommend JSON for its simplicity and automatic transformations available, although this may not always apply. Manually building a JavaScript value (i.e., without the JSON library) should be done with caution, since it is fairly easy to enter incorrect, malicious, or other unexpected output.

+1
source

Instead of manually launching my own solution, I would recommend using a library such as Newtonsoft.Json.

http://james.newtonking.com/pages/json-net.aspx

Why reinvent the wheel?

+1
source
 $.each('[' + string.Join(',', arrTickerContents), + ']', function (i, objValue) { 
0
source

All Articles