开发者

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

开发者 https://www.devze.com 2023-01-15 19:29 出处:网络
I have the following code, which works perfectly fine in every browser except for IE <script type=\"text/javascript\">

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开发者_如何学Python.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 ^_^).


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#.


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 %>" });
<% } %>         


<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>
0

精彩评论

暂无评论...
验证码 换一张
取 消