1

For my project, I would like to dynamically display a table containing information from my database. Unfortunately, I am unable to pass the c# array containing all of my database's information into a Javascript array. I have tried creating a hidden field like this:

<input type="hidden" id="tutors" name="tutors" value="<%: PeerTutoring.StaticData.GetTutorsSerialized()%>" />

The method GetTutorsSerialized is:

public static string GetTutorsSerialized()
    {
        char[] stuff = new JavaScriptSerializer().Serialize(new PeerTutoring.Models.PeerTutoringDataContext().Tutors).ToArray();
        return stuff.ToString();
    }

Next, I have tried accessing this information from Javascript like this:

var x = $('#tutors').val()
        alert(x);

This displays the message "System.Char[]" in the alert box. The length of the 'x' is also 13, which is the length of the string "System.Char[]".

Also, once I have got this array working, will I be able to access fields of the object's held in the Javascript array like this? :

x[0].Email

Thanks for the help.

tereško
  • 58,060
  • 25
  • 98
  • 150
user1162850
  • 101
  • 2
  • 10

2 Answers2

1

Why not pass the data to the view using a view model and use c# to generate the table?

<table>
    <%
        foreach(var m in Model)
        { %>
            <tr>
                <td><%: m.Property1 %></td>
                <td><%: m.Property2 %></td>
            </tr>
        <% }
    %>
</table>

For more info on passing data to a view in MVC: http://blogs.msdn.com/b/nunos/archive/2010/02/04/quick-tips-about-asp-net-mvc-how-do-i-pass-data-to-a-view.aspx

bitwiser
  • 221
  • 2
  • 9
  • 1
    I will be changing the table dynamically, based on the value's of other controls on the page. I do not think this plan would allow me to change the table dynamically. – user1162850 Jun 14 '13 at 01:51
1

Instead of .toString(), try new string(stuff);

.NET / C# - Convert char[] to string

Community
  • 1
  • 1
norepro
  • 777
  • 2
  • 9
  • 18