Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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){
      if(firstItem)
      {
         firstItem = false;
      }
      else
      {%>
        ,
      <%}%>
     '<%:item%>'
  %>

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

share

locked by Jamal Jul 30 '14 at 17:06

This question exists because it has historical significance, but it is not considered a good, on-topic question for this site, so please do not use it as evidence that you can ask similar questions here. This question and its answers are frozen and cannot be changed. More info: help center.

up vote 6 down vote accepted

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

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

Use the JavaScriptSerializer from System.Web.Extensions

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

share

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.

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

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