admin管理员组文章数量:1356461
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!
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!
Share Improve this question edited Jul 1, 2012 at 23:33 tereško 58.5k25 gold badges100 silver badges150 bronze badges asked Apr 2, 2012 at 16:28 mishapmishap 8,52514 gold badges62 silver badges93 bronze badges3 Answers
Reset to default 4Did you try wrapping the contents in <text>
tags?
var carsArray = new Array();
@foreach (var item in Model)
{
<text>carsArray.push("@item.Property")</text>
}
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);
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
本文标签: aspnet mvcIterating through IEnumerable Model in JavaScriptStack Overflow
版权声明:本文标题:asp.net mvc - Iterating through IEnumerable Model in JavaScript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743997200a2573210.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论