1

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 ?

1 Answer 1

1

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

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

5 Comments

You'll need to add @: before the call to your javascriptFunc. I forgot that in my original post. This instructs razor to output the line as plain text.
Per your conditional compilation, from stackoverflow.com/questions/6655696/…, you'll need to add /*@cc_on @*/ in your code.
where in the code do I need to add /*@cc_on @*/ ? within script tags.
I dont think it matters, but I would defer you to the referenced question. But try adding it at the top of your view after the @model statement
Error'cc_on' does not exist in the current context ?? no matter where I place it ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.