Arka Chatterjee
Arka Chatterjee

Reputation: 327

How to access the elements of a list of array passed from the controller in javascript?

I am using Asp.net MVC and in the controller I have a function that generates a list of array i.e. List and after converting it to a view I am returning this to the view page.In the view page I am converting it to List by the following code:

          <% List<string[]> items = (List<string[]>)ViewData["Items"];  %>

Now I want to access the elements one by one of each array belonging to the list using for/foreach statement in the javascript.I am trying the following code:

            var j;
            for(j=0;j<'<%=items.Count%>';j++)
            {
                   alert('<%=items['+j+'].GetValue(0).ToString()%>');
                   ..........                                         
            }  

But, I am getting the error : "Too many characters in character literal".If I use the following code then it is working fine:

                    alert('<%=items[0].GetValue(0).ToString()%>'); 

But I want to use it dynamically.Is there any way to do this operation?Please Help me.Thanks in advance. Arka

Upvotes: 0

Views: 614

Answers (2)

Aliaksei Kliuchnikau
Aliaksei Kliuchnikau

Reputation: 13719

You need to serialize the server-side list object into javascript array:

Example C# function to serialize object:

protected string SerializeToJson(List<string[]> list) {
        if ( list != null && list.Count > 0 ) {
            var stream = new MemoryStream();
            var jsSerializer = new DataContractJsonSerializer(list.GetType());
            jsSerializer.WriteObject(stream, list);

            return Encoding.UTF8.GetString(stream.ToArray());
        }
        return string.Empty;
    }

Usage example (JavaScript with inlined call to C# JSON serialization function):

// the following call will return JSON array [["a","b"]]
var arrayFromServer = <%= SerializeToJson(new List<string[]> { new [] {"a", "b"}};) %>;

Is this what you were asking for?

Upvotes: 2

Alexander Prokofyev
Alexander Prokofyev

Reputation: 34515

You could process elements of the list only on the server side in this scenario.

Upvotes: 0

Related Questions