Reputation: 355
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;
}
Upvotes: 2
Views: 12305
Reputation: 355
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>
Upvotes: 1
Reputation: 20640
Try something like this (Note: I had a file already setup so the name is different):
<script type="text/javascript">
$(function ()
{
$.ajax({
url: "WebService.asmx/GetListData",
success: OnSuccess,
error: OnError
});
});
function OnSuccess(data)
{
for (var i = 1; i < data.all.length; i++)
{
alert(data.all[i].textContent);
}
}
function OnError(data)
{
alert(data.statusText);
}
</script>
Upvotes: 0
Reputation: 231
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);
Upvotes: 2