views:

111

answers:

2

Hello,

I am tring to add data to a listbox in javascript, however the string building syntax has me stumped:

var yourobject = '<%=Model.Inserts['+ i + ']%>';

causes an error: "Too many characters in character literal"

All of the code:

var mlb = cm.createListBox('mylistbox', {
                        title: 'My list box',
                        onselect: function(v) {
                                tinyMCE.activeEditor.windowManager.alert('Value selected:' + v);
                            }
                        });


                        for (var i = 0; i < '<%=Model.Inserts.Count() %>'; i++) {
                            var yourobject = '<%=Model.Inserts['+ i + ']%>';
                            mlb.add(yourobject, i);
                        }
+2  A: 

You will need to loop through your Model object in a .NET code block, and assign those values to your JavaScript variables in that loop:

var count = 0, yourobject; // This is JavaScript

<% for (var i = 0; i < Model.Inserts.Count(); i++) { %> // This is .NET 
       yourobject = '<%= Model.Inserts[i] %>'; // This is JS AND .NET
       mlb.add(yourobject, count++); // This is JavaScript
<% } %>
Noah Heldman
Wouldn't this output multiple `var yourobject...` statements? That would be a javascript error. I think you'd need to declare it outside the loop as well and simply reuse it inside the loop.
tvanfosson
Edited based on your comment...thanks!
Noah Heldman
+2  A: 

You can't mix code that runs on the server (the transliteration of the <% %> block) with that the runs on the client (the for loop) in that way. Do the iteration in C# rather than in javascript and create a javascript object in a string that you can simply assign.

<%  var aray = "[";
    foreach (var insert in Model.Inserts) {
        aray += "'" + insert + "',";
    }
    aray = aray.TrimEnd(",") + "]";
 %>
    var mlb = <% aray %>;
tvanfosson