How to call c# method with no parameters and access returned data?
If your method takes no arguments, just don't specify the data property on the ajax call
<script>
$(function () {
$.ajax({
url: 'WebService.asmx/getList',
type: 'POST',
dataType: 'json', //make sure your service is actually returning json here
contentType: 'application/json',
success: function (data, status) {
//here data is whatever your WebService.asmx/getList returned
//populate your dropdown here with your $.each w/e
}
});
});
</script>
Also I could be wrong, but the WebService method you showed, doesn't look like it will return json. I think you will have to serialize, or set the content type or something similar. (Been along time since I've used the asmx type services)
loonyuni
Updated on June 14, 2022Comments
-
loonyuni almost 2 years
So I have seen many examples such as these : https://stackoverflow.com/a/8094230/2525507
public class WebService : System.Web.Services.WebService { [WebMethod] public List<string> getList() { return new List<string> {"I", "Like", "Stack", "Overflow"}; } }
Where you just it seems that through the success function you can view the returned data from the c# method in the form of an alert. But what if I want to access this "input+1" data outside of the function call, how would I proceed to do that? Also I am not sure how to call a method that has no parameters?
<body> <select id="wordSelect"> // Drop Down Menu to be populated </select> <script> $(function () { $.ajax({ url: 'WebService.asmx/getList', data: '{**NO PARAMETERS?!**}', // should I also call JSON.stringify? type: 'POST', dataType: 'json', contentType: 'application/json', success: function (data, status) { alert(data); alert(typeof data); } }); }); $.each(data.i, function(index, item) { // will this access "I", "Like", ... etc? $(#wordSelect).append( $("<option></option>") .text(item) ); }; </script> </body>
In the end, I would like to populate a dropdown list using returned JSON data from a c# method that has been called through ajax, but I'm not sure how I can play with that retrieved JSON data that seems to be stuck in the function call?
Sorry, I am new to Jquery/AJAX/etc... But Thank you so much!
-
loonyuni almost 10 yearsThank you guys! Sorry this was such a trivial question, but I really couldn't Google with the correct terminology or find apt examples. Thank you thank you thank you!
-
loonyuni almost 10 yearsSo I have tried to just access data in my success call, but I keep getting an error saying "data" is undefined? Any ideas?
-
Kyle Gobel almost 10 yearsis data the first parameter of your success callback?
-
loonyuni almost 10 yearsIt's all good turns out my my webservice was nested and I messed up the url.