0

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?

3 Answers 3

2

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 + "')");
 }
}
Sign up to request clarification or add additional context in comments.

Comments

1

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
}

Comments

1

You could use something like this:

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

}

Comments

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.