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

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|improve this question
add comment (requires an account with 50 reputation)

3 Answers

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|improve this answer
Oh I really like that. – stimms Feb 21 '11 at 1:33
1  
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
add comment (requires an account with 50 reputation)

Use the JavaScriptSerializer from System.Web.Extensions

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

share|improve this answer
add comment (requires an account with 50 reputation)

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|improve this answer
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
add comment (requires an account with 50 reputation)

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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