如何在没有参数的情况下调用c#方法并访问返回的数据? [英] How to call c# method with no parameters and access returned data?

查看:130
本文介绍了如何在没有参数的情况下调用c#方法并访问返回的数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我见过很多这样的例子:
https://stackoverflow.com/a/8094230/2525507

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"};
   }
}

你只是通过成功函数看来可以以警报的形式从c#方法查看返回的数据。但是如果我想在函数调用之外访问这个input + 1数据怎么办呢,我该怎么做呢?另外我不知道如何调用没有参数的方法?

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>

最后,我想使用已通过ajax调用的ac#方法返回的JSON数据来填充下拉列表,但我不确定如何使用那些似乎停留在函数调用中的检索到的JSON数据?

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?

对不起,我是Jquery / AJAX /等​​的新手...但是非常感谢你!

Sorry, I am new to Jquery/AJAX/etc... But Thank you so much!

推荐答案

如果你的方法不带参数,就不要在ajax调用上指定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>

我也错了,但是你展示的WebService方法似乎不会返回JSON。我认为你必须序列化,或设置内容类型或类似的东西。 (自从我使用asmx类型服务以来一直沿着时间)

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)

这篇关于如何在没有参数的情况下调用c#方法并访问返回的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆