0
    <script type="text/javascript">
        window.onload = function () {
            for (var i=0;i<@Model.listsinfo.Count;i++)
            {
                $('#work').append($('<div class="col-md-3" id="temp"><label for="text1">'+ '@Model.listsinfo[i].Label' +'</label></div><div class="col-md-3"> <input type="text" placeholder="Alerts" class="form-control" id="text1"> </div>'));
            }
       }
   </script>

In the above code, I am passing a list from my controller and trying to iterate it. But @Model.listsinfo[i].Label is not working and the error says 'i' does not exist in the current context. I am able to access the list value by giving index values @Model.listsinfo[0].Label but iterations are not working. Any help is appreciated.

12
  • remove the single quotes from '@Model.listsinfo[i].Label' Commented Oct 20, 2017 at 9:19
  • 2
    Your @Model.listsinfo is located on server and your loop - on client Commented Oct 20, 2017 at 9:19
  • @Flying it's possible to access them in razor Commented Oct 20, 2017 at 9:20
  • @Niladri ok, my bad, sorry :) Commented Oct 20, 2017 at 9:20
  • 1
    Why use a Javascript event to generate HTML instead of letting Razor generate that HTML for you? Commented Oct 20, 2017 at 10:11

1 Answer 1

2

You can use Json.Encode with Html.Raw and assign it to a JavaScript array, then iterate the contents from there:

<script type="text/javascript">
    window.onload = function () {
            var array = @Html.Raw(Json.Encode(@Model.listsinfo));

            for (var i = 0; i < array.length; i++)
            {
                $('#work').append($('<div class="col-md-3" id="temp"><label for="text1">'+ array[i].Label +'</label></div><div class="col-md-3"> <input type="text" placeholder="Alerts" class="form-control" id="text1"> </div>'));
            }
    }
</script>

Note that Model.listinfo processed at server-side and iteration occurs in client-side, so you need to convert viewmodel array to JS array first, then you can assign it to append method.

Similar issues:

MVC: Iterating a Viewbag array in javascript

jQuery: How to traverse / Iterate over a list of object

Sign up to request clarification or add additional context in comments.

1 Comment

You can consider to accept any answer that best solving your problem rather than saying "thanks", there's no obligation to do so.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.