简体   繁体   中英

asp.net mvc - how can you loop through model data in javascript

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

I know this is an old question, but the answers are outdated, as it is now possible.

This can be done in the razor syntax using @: on the start of the lines to run in javascript (escape from c#).

My Model.xValues is a List<String> passed from the controller. and yValues is List<int>

Here is a quick example of how to loop through a model data inside a javascript function.

<script type="text/javascript">
   function drawChart() {

        // Create the data table.
        var data = new google.visualization.DataTable();
        data.addColumn('string', '@Model.LabelName');
        data.addColumn('number', '@Model.ValueName');

       @for(int i = 0; i < Model.xValues.Count; i ++)
       {
           @: data.addRow(['@Model.xValues.ElementAt(i)', @Model.yValues.ElementAt(i)]);
       }

       ... etc

</script>

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 %>;

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
<% } %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM