rism
rism

Reputation: 12142

How to return an array as a string?

I want to create an array in an MVC controller and embed it into a page so that it can be used by jQuery.

If i go:

var arr = new[]{"abc", "bca", "xyz"};
ViewBag.MyArray= arr.ToString();

I get System.String[] in the web page.

If I go

this.ViewBag.StartupScript = Json(new { flag = "en_GB", flag = "ro_RO" }).Data;

It wont compile, duplicate anonymous type property named flag.

Upvotes: 0

Views: 132

Answers (2)

Magus
Magus

Reputation: 1312

If your goal is to make a string out of an array, you want: string.Join('delimiter', arr)

As for your second example, you clearly can't name two properties the same thing on the same object.

Of course, your question is somewhat wrong, and may be better answered by another answer, where your meaning was deduced.

Upvotes: 1

haim770
haim770

Reputation: 49095

First, you need to pass it to the View:

ViewBag.MyArray = arr;

Then in the View:

<script type="text/javascript">
var arr = @Html.Raw(Json.Encode(ViewBag.MyArray));
</script>

Upvotes: 0

Related Questions