MVC2:在ViewData中传递字符串数组,无法在Javascript中使用

时间:2013-07-02 06:24:38

标签: asp.net-mvc

以下是在ViewData中返回Arrays的控制器操作。

  ViewData["arrayTotalCertificateCount"] = arrayTotalCertificateCount;
        ViewData["_CertificateCategory"] = _CertificateCategory;
        ViewData["arrayCodeSeries"] = arrayCodeSeries;
        ViewData["arrayCodeCounts"] = arrayCodeCounts;

        return PartialView();

现在,在View中,javascript,我无法访问它们。

以下是我在View Javascript中编写的代码。

 var arrayTotalCertificateCount = new Array();
    var i =0;

    for(var item in <%= ViewData["arrayTotalCertificateCount"]%>)
    {    
        arrayTotalCertificateCount[i] = item;
        i=i+1;
    }

它会像 -

那样抛出错误
 for(var item in System.String[])
Uncaught SyntaxError: Unexpected token ]

任何人都可以帮我在javascript数组变量中转换这个ViewData数组吗?

1 个答案:

答案 0 :(得分:1)

试试这个

<% var serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); %>
var arrayTotalCertificateCount = <%= serializer.Serialize(ViewData["arrayTotalCertificateCount"]) %>;
for(var item in arrayTotalCertificateCount )
{    
   arrayTotalCertificateCount[i] = item;
   i=i+1;
}