【问题标题】:API Data not showing on the click eventAPI 数据未显示在点击事件中
【发布时间】:2019-05-28 22:31:21
【问题描述】:

我正在从 Web API 检索数据。现在,当我单击“按名称获取”按钮时,它会显示项目。

我的视图代码如下。

 <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <input type="text" name="name1" id="text1" value="" />
    <input type="button" name="name2" id="btn2" value="Get by names" />
    <ul id="names"> </ul>
    <script>

        $(document).ready(function () {
            $("#btn2").click(function () {
                $("#names").empty();
                $.getJSON("/api/Customer/", function (data) {
                    $.each(data, function (key, val) {
                        $("<li>" + val + "</li>").appendTo($("#names"));

                    })
                })

            })


    </script>

Web API 控制器数据如下:

 namespace theapis.Controllers
    {


        public class CustomerController : ApiController
        {
            private static List<string> studentnames = new List<string> { "Ammad", "Ali", "Khan" };

            public IEnumerable<string> GetvalueByIndex(){

             return customernames;
            }    

        public string Getnames(int id)
            {
                return customernames[2];
            }

        }
    }

结果应该显示列表。 阿马德 阿里 汗

【问题讨论】:

  • 你的 ajax 调用是否命中了控制器方法?
  • Uncaught SyntaxError: Unexpected end of input 。控制台显示错误。

标签: c# jquery asp.net-web-api


【解决方案1】:

您的代码中有多个问题。

您将 url 指定为:

$.getJSON("/api/Customer/"

按照惯例,Web API 将在 Customer 控制器中查找 Get 方法,而控制器中没有名称为 Get 的方法。您需要更改控制器中的名称或寻找以不同于约定的名称调用操作方法的方法。

一种快速的方法是重命名操作方法:

public string Get()
{
     private List<string> studentnames = new List<string> { "Ammad", "Ali", "Khan" };
     return customernames;
}

您还缺少document.ready 的括号结束。那段代码是这样的:

 $(document).ready(function () {
        $("#btn2").click(function () {
            $("#names").empty();
                $.getJSON("/api/Customer/", function (data) {
                     $.each(data, function (key, val) {
                         $("<li>" + val + "</li>").appendTo($("#names"));

                     }); // $.each closing
                }); // $.getJSON closing

          }); // button click closing
 }); // document.ready closing

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-01
    • 1970-01-01
    • 2014-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多