Iterating through IEnumerable Model in JavaScript

I have an IEnumerable <> of Car (here it won't let me use angle brackets correctly) used in my opinion: and in my JavaScript I have to create an object array corresponding to the object in my model. I have a problem repeating my model in JavaScript If I use a razor the javascript code doesn't work :

<script type="text/javascript">

var carsArray = new Array();     

@foreach (var item in Model)
{
    //add the and item to carsArray object
}

//OR
for(i=0;i<@Model.Count();i++)
{
    alert(@Model.ElementAt(i).Title);

      

// Error: the name "i" does not exist in the current context

 //add to array

}

</script>

      

Thank!

+3


source to share


2 answers


You are mixing server and client code.

If you want to spit out client side code on the server, you can.

But your best bet is to serialize the model data to JSON and put it on the client.




Example:

Update

@{
   var js = new JavaScriptSerializer();
}

myJavascriptObject.Models = @js.Serialize(myModels);

      

+3


source


Have you tried wrapping the content with tags <text>

?



var carsArray = new Array();     

@foreach (var item in Model)
{
    <text>carsArray.push("@item.Property")</text>
}

      

+4


source







All Articles