1

I am trying to iterate the contents of a string array, that was put in the ViewBag by the controller, in javascript.

In the controller:

ViewBag.Addresses = new string[] {"a", "b", "c"};

And in the view:

<script language="javascript" type="text/javascript">
    function ExecuteOnLoad() {

        var array = How do I get "a", "b" and "c" here?;
        for (var i = 0; i < array.length; i++) {
            doSomething(array[i]);
        }
    }

</script>

I searched a lot for an answer but seem to find solutions only for the razor view engine. What about web forms?

1 Answer 1

2

In your view

<script language="javascript" type="text/javascript">
    function ExecuteOnLoad() {

        var array = <%= Html.Raw(ViewBag.Addresses)%>;
            for (var i = 0; i < array.length; i++) {
                document.write(array[i]);
            }
        }
</script>

Then from within your controller:

JavaScriptSerializer js = new JavaScriptSerializer();
//serializes array into json

ViewBag.Addresses = js.Serialize(new[] { "a", "b", "c" });

Personally I'd look at creating a View model and serializing the array in to a property on the view model and then doing this in your view:

<script language="javascript" type="text/javascript">
    function ExecuteOnLoad() {

        var array = <%= Html.Raw(Model.Addresses)%>;
            for (var i = 0; i < array.length; i++) {
                document.write(array[i]);
            }
        }
</script>
Sign up to request clarification or add additional context in comments.

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.