3

I have an IEnumerable<> of Car(here it wont let me use angle brackets properly) model used in my view : and in my JavaScript I have to create an array of object corresponding to object in my model. I have trouble iterating through my model in JavaScript If I use razor, the javascript code is not working:

<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 you!

tereško
58.5k26 gold badges100 silver badges151 bronze badges
asked Apr 2, 2012 at 16:28

3 Answers 3

4

Did you try wrapping the contents in <text> tags?

var carsArray = new Array(); 
@foreach (var item in Model)
{
 <text>carsArray.push("@item.Property")</text>
}
answered Apr 2, 2012 at 16:31
Sign up to request clarification or add additional context in comments.

Comments

3

You are mixing server side and client side code.

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

But best is to serialise your model data into JSON and put it on the client.


Rough example:

Update

@{
 var js = new JavaScriptSerializer();
}
myJavascriptObject.Models = @js.Serialize(myModels);
jessegavin
75.8k28 gold badges141 silver badges165 bronze badges
answered Apr 2, 2012 at 16:32

1 Comment

thank you. Any simple example or article that I could refer to ? Thanks,
1

another way to do this is to just convert the server model to javascript, and then iterate it.

you can convert it like so:

var model = @Html.Raw(Json.Encode(Model));

this method worked for me. solution taken from another stackoverflow answer:

Accessing MVC's model property from Javascript

answered Jun 14, 2021 at 17:15

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.