JQuery ajax return list from c# function

11,318

Solution 1

Well after careful research I realized that I was going about my problem the wrong way. I wanted to have C# communicate with javascript/html for a web form in the same project. Using a list was a bad idea as my javascript couldnt effectively see it unless I formatted it as one big JSON String. Here is the updated code that solved my problem, hopefully it helps someone down the line. [ComVisible(true)] allows the external window named test to see my c# function, and the $.parseJSON(myarray) was able to parse my JSON string into a usable array.

c#

[ComVisible(true)]
public string GetData()
{
    string test = "[{"Name": "test1"}, {"Name": test2"}, {"Name": "test3"}]";
    return test;
}

javascript

<script type="text/javascript">
            var test = window.external;
            var myarray = test.GetData();
            var obj = $.parseJSON(myarray);
            alert(obj[1].Name);
        }

   </script>

Solution 2

Pulled from this thread:

You can serialize that list into some nice tidy JSON like this:

using System.Web.Script.Serialization;
var jsonSerialiser = new JavaScriptSerializer();
var json = jsonSerialiser.Serialize(aList);
Share:
11,318
wheatfairies
Author by

wheatfairies

Updated on June 04, 2022

Comments

  • wheatfairies
    wheatfairies almost 2 years

    I'm a bit confused when trying to implement C# and jquery to work together. I have a .cs file and a javascript document in the same solution/project. My c# function returns a list of strings, which I would like to append to some HTML data using Javascript. I am also using a webform for my HTML. Is it possible to return my list on the javascript side?

    javascript

    $(function () {
        $.ajax({
            type: "GET",
            url: "Test/GetListData", 
            dataType: "data: Array<any>" //Something like this?
        });
    
        //Can i return the list and use it here?
    });
    

    c# method

    public List<string> GetListData()
    {
        List<string> mylist = new List<string>();
        mylist.Add("test1");
        mylist.Add("test2");
        mylist.Add("test3");
        return mylist;
    }
    
  • wheatfairies
    wheatfairies over 9 years
    So is it necessary to serialize my list to JSON in order to use the data in JQuery?
  • Michael Anthopolous
    Michael Anthopolous over 9 years
    It'd be the easiest way to go about it. JSON objects are light and easily parsed by jQuery.
  • wheatfairies
    wheatfairies over 9 years
    Thanks for the tip. See my updated answer below for how I solved my issue.
  • user1017102
    user1017102 over 7 years
    Did you mean: {"Name": "test2"}, instead of {"Name": test2"} ?