Search code examples
c#javascriptserializationjavascriptserializer

JavaScript().Serializer() gets [object, object]


I can am trying to serialize some code from C# into JavaScript so I can use it in the client side. However when I do this it fetches [object Object],[object Object],[object Object], however if I pass a normal string say "Hello", it works fine, so the serialize doesn't seem to be the problem.

So my C# code looks like:

protected void Page_Load(object sender, EventArgs e)
{
    List<YearMonthGrid> ymgs = new List<YearMonthGrid>();
    ymgs = DAL.GetYearMonthGrid("value");


    var m = from c in ymgs where c.Month == 7 select c;

    v1 = new JavaScriptSerializer().Serialize(m);
}

and my JS code looks like:

var d1 = <%=this.v1%>;
document.write(d1);

The class YearMonthGrid has three properties which I use in the list:

  • Name (String)
  • Quantity (int)
  • Month (int)

When I debug it, my value v1 contains the string I want to return, however when I try to get it, it just shows me Object over and over. Any ideas to why this is?


Solution

  • When converting an object to a string (i.e. writing it out to a page) then it will write out [object Object] instead of the contents of the object. Instead, try doing something like this:

    var d1 = <%=this.v1%>;
    for (var i = 0; i < d1.length; i++) {
        var yearMonthGrid = d1[i];
        document.write(yearMonthGrid.Name + '<br />');
        document.write(yearMonthGrid.Quantity + '<br />');
        document.write(yearMonthGrid.Month + '<br />');
    }
    

    If you're running this in Firefox or Chrome (I haven't tried in newer versions of other browsers) then you could also do this to see the contents of each object:

    var d1 = <%=this.v1%>;
    for (var i = 0; i < d1.length; i++) {
        console.log(d1[i]);
    }
    

    Just make sure you have your JavaScript console open.