1

Hi I tried to pass a list of self-defined objects to JQuery as parameter and expect jQuery recognise it as the specific object and loop through it. The class is:

public class PriceSummary{
        public string ItemName { get; set; }
        public string ItemPrice { get; set; } } 

The backend method is:

public void updatePriceSummary(List<PriceSummary> PriceSummaryList){
        ScriptManager.RegisterStartupScript(Page, GetType(), "changePriceList",
           "updatePriceList('" + PriceSummaryList + "');", true);}

JQuery Method

function updatePriceList(PriceSummaryList) {
    PriceSummaryList.each(function () 
      {$('#ControlSummaryTitle').append('<tr id = "xxx"> <td class="SummaryItem">' +
      this['ItemName'] + '</td> <td class="SummaryPrice">' + this['ItemPrice'] + 
      '</td></tr>');   })
;}

However, the JQuery function couldn't recognise the parameter as a list and couldn't loop through it. The error message is:

0x800a01b6 - JavaScript runtime error: Object doesn't support property or method 'each'

Could anybody advise how to fix it?

DennisL
  • 293
  • 1
  • 3
  • 12

2 Answers2

2

Problem 1: if you're just composing a List<> into a string it will get turned into a string by the simplest method .Net knows, which is .ToString(), resulting in "System.Collections.Generic.List`1[someclass]". You need to transform it into something that Javascript understands, let's say by serializing it into JSON. You can easily inspect the value in the browser to see if you're getting closer to something that works.

Problem 2: you're surrounding the value with single quotes (updatePriceList('...')) so it would still be interpreted as a string; remove the single quotes.

Alex Paven
  • 5,539
  • 2
  • 21
  • 35
  • Hi Alex, thanks for your answer! Could you please advise how to transform it into e.g. Json format ? – DennisL Mar 31 '17 at 00:45
  • Well, use a JSON serializer - there are some included with .Net but I've always used thrid party ones, but anyway see http://stackoverflow.com/questions/3275863/does-net-4-have-a-built-in-json-serializer-deserializer – Alex Paven Mar 31 '17 at 00:48
2

Just serialize your list to JSON before you send it across (almost identical issue) Converting list of objects to json array

Community
  • 1
  • 1
asolvent
  • 821
  • 13
  • 26