从jQuery的调用的WebAPI [英] Calling WebApi from jQuery

查看:941
本文介绍了从jQuery的调用的WebAPI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

刚开始的WebAPI,并有多个问题。阅读吨的信息,但可能缺少一些概念。

在我的控制器:

 公开的IEnumerable<产品与GT;的GetProducts()
    {
        返回db.Products.AsEnumerable();
    }
    公共产品GetProduct(字符串名称)
    {
        产品产品= db.Products.FirstOrDefault(P => p.Name ==名);
        如果(产品== NULL)
        {
            抛出新的Htt presponseException(Request.CreateResponse(的HTTPStatus code.NotFound));
        }        返回产品;
    }

使用Javascript:

  $('#搜索')。点击(函数(){
    jQuery.support.cors = TRUE;
    。VAR产品名称= $('#名称)VAL();    $阿贾克斯({        网址:HTTP://本地主机:62178 / API /产品,
        // URL:HTTP://本地主机:62178 / API /产品/+产品名称,
        键入:GET,
        成功:功能(数据){
            alertData(数据);
        }
    });
});

首先,如果我传递一个参数产品名称不管,无参数GetProduct被调用(而且应该将数据返回)。 我需要能够调用这两个GET方法。
其次,成功的函数没有被调用。所以我不从的WebAPI方法得到任何数据了。

任何提示或指导是AP preciated。谢谢。
WebApiConfig.cs

 公共静态类WebApiConfig
{
    公共静态无效的注册(HttpConfiguration配置)
    {
        config.Routes.MapHttpRoute(
            名称:DefaultApi
            routeTemplate:API / {}控制器/(编号),
            默认:新{ID = RouteParameter.Optional}
        );
    }
}

唯一的问题,现在是,我没有得到我的警报数据:

  $('#搜索')。点击(函数(){
    jQuery.support.cors = TRUE;
    。VAR产品名称= $('#名称)VAL();    $阿贾克斯({        网址:HTTP://本地主机:62177 / API /产品/+产品名称,
        //数据:{名称:产品名称},
        键入:GET,
        数据类型:JSONP
        错误:功能(请求,状态,错误){
            警报(request.responseText);
        },
        成功:功能(数据){
            警报(数据);
        }
    });
});


解决方案

更改或者您的方法签名,以

 公共产品GetProduct(字符串ID)

或者你的路由

  routeTemplate:API / {控制器} / {name}的

方法参数的名称确定选择的路线。

Just started with WebApi and have multiple problems. Read tons of info, but probably missing some concepts.

In my controller:

    public IEnumerable<Product> GetProducts()
    {
        return db.Products.AsEnumerable();
    }


    public Product GetProduct(string name)
    {
        Product product = db.Products.FirstOrDefault(p => p.Name == name);
        if (product == null)
        {
            throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
        }

        return product;
    }

Javascript :

 $('#Search').click(function () {
    jQuery.support.cors = true;
    var productName = $('#Name').val();

    $.ajax({

        url: "http://localhost:62178/api/product",
        //url: "http://localhost:62178/api/product/" + productName,
        type: "GET",
        success: function (data) {
            alertData(data);
        }
    });
});

First of all, no matter if I pass a parameter productName, the parameterless GetProduct is called (and should return data back) . I need to be able to call both of these GET methods. Second, the success function is not called. so I don't get any data back from WebApi methods.

Any tips or guidance is appreciated. Thanks. WebApiConfig.cs

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

Only problem right now is that I don't get my data alerted :

$('#Search').click(function () {
    jQuery.support.cors = true;
    var productName = $('#Name').val();

    $.ajax({

        url: "http://localhost:62177/api/product/" + productName,
        //data: { name: productName },
        type: "GET",
        dataType: "jsonp",
        error: function (request, status, error) {
            alert(request.responseText);
        },
        success: function (data) {
            alert(data);
        }
    });
});

解决方案

Change either your method signature to

public Product GetProduct(string id)

Or your route to

routeTemplate: "api/{controller}/{name}"

The name of your method parameters determines the route selected.

这篇关于从jQuery的调用的WebAPI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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