I often run into the problem of producing a javascript array on an ASP.net page from an IEnumerable and I was wondering if there was an easier or clearer way to do it than

<% bool firstItem = true;
   foreach(var item in items){
         firstItem = false;

The whole thing is made much more verbose because of IE's inability to handle a hanging comma in an array or object.


3 Answers 3


With a bit of help from System.Linq this becomes quite easy.

var array = [ <%= 
    string.Join(",", items.Select(v => "'" + v.ToString() + "'").ToArray())  
%> ];
  • \$\begingroup\$ Oh I really like that. \$\endgroup\$
    – stimms
    Commented Feb 21, 2011 at 1:33
  • 2
    \$\begingroup\$ I really do hope the items never contain an apostrophe character or the </script> character sequence. A good solution would guard against these possibilities. \$\endgroup\$
    – Timwi
    Commented Feb 24, 2011 at 15:55
  • \$\begingroup\$ The answer below should properly handle that: codereview.stackexchange.com/questions/881/… \$\endgroup\$
    – Bertvan
    Commented Oct 9, 2013 at 14:12

Use the JavaScriptSerializer from System.Web.Extensions

<%: new JavaScriptSerializer().Serialize(items) %>


You can use an anonymous class and DataContractJsonSerializer and do something like this:

var toSerialize = items.Select(x => new { JSProp = x.ItemProp }).ToList();

var serializer = new DataContractJsonSerializer(toSerialize.GetType());
MemoryStream ms = new MemoryStream();
serializer.WriteObject(ms, myPerson);
string json = Encoding.Default.GetString(ms.ToArray());

I like this approach because you can create complex javascript types in a simply way.

Sorry if it does not compile but I'm not with a dev machine.

  • \$\begingroup\$ I would find this cleaner and more robust if it used using clauses for the stream and the serializer. \$\endgroup\$
    – Timwi
    Commented Feb 24, 2011 at 15:57
  • \$\begingroup\$ Yeah, sure! The idea was to show the anonymous type generation with LINQ \$\endgroup\$
    – tucaz
    Commented Feb 25, 2011 at 0:15

Not the answer you're looking for? Browse other questions tagged or ask your own question.