1

Below is the controller action which returns Arrays in ViewData.

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

        return PartialView();

Now, in View, javascript, I am not able to access them.

Below is the code I have written in View Javascript.

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

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

It throws error like -

 for(var item in System.String[])
Uncaught SyntaxError: Unexpected token ]

Can anyone please help me to convert this ViewData array in javascript array variable?

1 Answer 1

1

Try this

<% 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;
}
Sign up to request clarification or add additional context in comments.

3 Comments

Satpal, thank you so much for quick reply. I tried your solution and I got rid of that error message. but Now I am getting below error. I think it is because of the space with numbers. I am not sure. var arrayTotalCertificateCount = "["5"," 5"," 1"]" Uncaught SyntaxError: Unexpected number Any idea, can I use item.Trim()?
Satpal, one more questions regarding this. I am getting CodeSeries as '70-158,70-169,70-181' from the controller and when I serialized it with var arrayCodeSeries = "<%= serializer.Serialize(ViewData["arrayCodeSeries"]) %>"; I am getting error message like - var arrayCodeSeries = "["\u002770-158,70-169,70-181\u0027","\u002770-158,70-177,70-181\u0027","\u002770-680\u0027",null,null]"; Uncaught SyntaxError: Unexpected token ILLEGAL --------- Can you please guide me on this?
I tried with var arrayCodeSeries = '<%= serializer.Serialize(ViewData["arrayCodeSeries"]) %>'; and it worked fine.. Thanks

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.