最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c# - ASP NET MVC array in controller to client side array - Stack Overflow

programmeradmin4浏览0评论

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.

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.

Share Improve this question edited Jul 10, 2013 at 22:33 coredump asked Jul 10, 2013 at 22:22 coredumpcoredump 3,1077 gold badges37 silver badges56 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 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>

Perhaps:

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

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

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>
发布评论

评论列表(0)

  1. 暂无评论