9
votes
\$\begingroup\$

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.

\$\endgroup\$

3 Answers 3

6
votes
\$\begingroup\$

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

var array = [ <%= 
    string.Join(",", items.Select(v => "'" + v.ToString() + "'").ToArray())  
%> ];
\$\endgroup\$
3
  • \$\begingroup\$ Oh I really like that. \$\endgroup\$ 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\$ Commented Feb 24, 2011 at 15:55
  • \$\begingroup\$ The answer below should properly handle that: codereview.stackexchange.com/questions/881/… \$\endgroup\$ Commented Oct 9, 2013 at 14:12
4
votes
\$\begingroup\$

Use the JavaScriptSerializer from System.Web.Extensions

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

\$\endgroup\$
1
vote
\$\begingroup\$

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.

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

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.