tags:

views:

82

answers:

2

Hi, 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

A: 

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

Alexander Prokofyev
+2  A: 

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?

Alex
Thank you very much.This is what I wanted.I have solved the problem.Thank you once again.
Arka Chatterjee