Grahame A
Grahame A

Reputation: 3953

ASP.NET MVC2 Generated Javascript contains comma that breaks script in Internet Explorer, code inside

I have the following code, which works perfectly fine in every browser except for IE

<script type="text/javascript">

   if (!window.slider) var slider = {}; slider.data = [<% foreach (var item in Model) {%>{ "id":"<%: item.ImageID %>", "client":"<%: item.ContentTitle %>", "desc":"<%: item.ContentDescription %>" },<%} %> ];

</script>

The problem is with the comma that separates each of the values being generated. Internet explorer throws a fit if there's a comma and no proceeding value so I need a way of generating this code without a comma on the last item in the collection. Am I approaching this the right way? Thanks, and see http://hub.mhn.co for the code in action (I welcome and appreciate any comments or feedback, as it's my first MVC site ^_^).

Upvotes: 0

Views: 206

Answers (3)

takepara
takepara

Reputation: 10433

<script type="text/javascript">

   if (!window.slider) var slider = {}; 
   slider.data = [<% = string.Join(",", Model.Select(item=> "{ id:\""+ item.ImageID +"\", client:\""+ item.ContentTitle "\", desc:\""+item.ContentDescription "\" }").ToArray())  ];

</script>

Upvotes: 1

Eugene Ramirez
Eugene Ramirez

Reputation: 3123

This should work

if (!window.slider) var slider = {}; 
slider.data = [];   
<% foreach (var item in Model) {%>
    slider.data.push({"id":"<%: item.ImageID %>", "client":"<%: item.ContentTitle %>", "desc":"<%: item.ContentDescription %>" });
<% } %>         

Upvotes: 1

Cristian Sanchez
Cristian Sanchez

Reputation: 32137

Yes, IE doesn't like trailing commas on arrays or objects. Fix that and it should work. A quick work around would be to store the strings in an array and then use the join operation/method for Strings in C#.

Upvotes: 2

Related Questions