mkell
mkell

Reputation: 731

How to use a foreach loop with an ILIST<models> in javascript?

Hi I have a razor view in my MVC 3 application using a @model IList<TrackerModel>

IList<TrackerModel> is being passed to the view from a action method in my controller. As the name suggests it's a list of TrackerModels.

I want to pass this list the the javascript block at the bottom of my view.

Run the list through a foreach loop so that each model makes use of a certain function. eg.

foreach(var mod in IList<TrackerModel>)
{
     LoadAttachments();
}

(I know the above is wrong, but you get the idea) Can this be done ?

   @foreach(var mod in Model)
{
    LoadAttachments(@Newtonsoft.Json.JsonConvert.SerializeObject(mod));
}

tried the above suggestion , and got the following errors. @foreach = condition compilation is turned off ?

var = Expected expression ?

in = expected ; ?

LoadAttachments = the name 'LoadAttachments ' does not exist in the current context ?

@Newtonsoft = condition compilation is turned off ?

Upvotes: 1

Views: 2142

Answers (1)

Philip Pittle
Philip Pittle

Reputation: 12295

If you want to take this approach (as opposed to having your javascript call back to a dedicated web service) is you're going to need to render your model into something your javascript can consume, like a json array.

For example in your View

 <script>
 @foreach(var mod in Model)
 {
      @:javascriptFunc(@Newtonsoft.Json.JsonConvert.SerializeObject(mod));
 }
 </script>

This will call your javascriptFunc for every item in your IList<TrackerModel>. Each TrackerModel is serialized using Newtonsfot.Json, which should be included automatically by Mvc, but if it's not in Mvc 3, you can add it via nuget: https://www.nuget.org/packages/Newtonsoft.Json

Upvotes: 1

Related Questions