5

My question is how ( if possible ) from an array like string[] a; that I pass it to the view through the ViewBag, how can I obtain a javascript array of strings.

I want to use this because I get a set of data from the DB and I want in the view to make chart and for that I need a javascript array.

3 Answers 3

8

It's easy to "render" an array to a Javascript object, using string.Join or similar:

@{
    ViewBag.a = new int[] { 1, 2, 3 };
    ViewBag.b = new string[] { "a", "b", };
}

<script type='text/javascript'>
    // number array
    var a = [ @(string.Join(", ", (int[])ViewBag.a)) ];
    console.log(a);  // [1, 2, 3]

    // string array -- use Html.Raw
    var b = [@Html.Raw("'" + string.Join("', '", (string[])ViewBag.b) + "'")];
    console.log(b);
</script>
Sign up to request clarification or add additional context in comments.

7 Comments

Great. One more question. If I have an original array of string and want to have a js array of strings ?
@coredump see my update -- you have to use Html.Raw for that, otherwise the quote marks get HTML-encoded.
@haim770 seems like a good idea, but @Html.Raw(Json.Encode(...)) is giving me weirdness. It renders & as "\u0026".
@haim770 That seems an elegant solution, but haw can you evade the problem McGarnagle raised ?
I haven't encountered such a problem with Json.Encode, but i trust @McGarnagle knows what he's talking about. however, your array doesn't contain & anyway, so just try var a = @Html.Raw(Json.Encode(new int[] {1,2,3})); and see if it's good for you.
|
1

Perhaps:

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

var newFoo = @Html.Raw(Json.Encode(@ViewBag.foo));

Comments

0

Controller

  public ActionResult Index()
    {
        int[] myArray = new int[] { 1, 3, 5, 7, 9 };
        ViewBag.myArray = myArray;
        return View();
    }

View

@{
    ViewBag.Title = "Index";
    var myArray = (int[])ViewBag.myArray;
    var myjsstring = "";
    for(int i =0;i<myArray.Length;i++)
    {
        myjsstring += "mycars[" + i.ToString() + "] = " + myArray[i] + ";";
     }
}

    <script type="text/javascript">
        var mycars = new Array();
        @myjsstring


    </script>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.