.Net pass a list of objects to JQuery as parameter

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?

c#
jquery
.net
asked on Stack Overflow Mar 30, 2017 by DennisL

2 Answers

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.

answered on Stack Overflow Mar 31, 2017 by Alex Paven
2

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

answered on Stack Overflow Mar 31, 2017 by asolvent • edited May 23, 2017 by Community

User contributions licensed under CC BY-SA 3.0