seth
seth

Reputation: 1389

Iterate through ViewData array and use javascript code

I have an array that is passed through the ViewData to my view. This array is composed of several elements of one of my Models.

I want to iterate through these elements and use javascript code with elements of the object.

Example in pseudo-code:

for x in ViewData["asdasd"] {

  foo(x.Property)

}

foo is a javascript function.

How can i do this?

Upvotes: 0

Views: 3255

Answers (3)

user1953110
user1953110

Reputation: 11

You could use something like this:

@{
foreach (var firstName in (ViewData["my_list"] as IEnumerable<string>)) {
    @Html.Raw(firstName);<br />
}

}

Upvotes: 1

McGarnagle
McGarnagle

Reputation: 102753

Use reflection to get the value. (edited because I realized I totally misunderstood the question at first)

@{ 
 Type t = typeof(MyModelType);
 foreach (string x in ViewData["mykey"])
 { 
     var propertyVal = t.GetProperty(x).GetValue(MyModelObject, null);
     @Html.Raw("foo('" + propertyVal + "')");
 }
}

Upvotes: 2

glarkou
glarkou

Reputation: 7101

If I am correct try:

var myArray = new Array();
myArray = <%= ViewData[yourarray] %>;

for (var i = 0; i < myArray.length; i++) {
    foo(myArray[i]);
    //Do something
}

Upvotes: 1

Related Questions