将数据发送到webapi GET请求Ajax调用

时间:2016-09-20 08:57:31

标签: jquery asp.net .net ajax asp.net-web-api

我在webapi中有以下模型类: -

public class SampleClass
    {
        public int id { get; set; }
        public string Name { get; set; }
    }

在Controller中获取方法: -

public string Get([FromBody]SampleClass sample)
        {
            return "value";
        }

我通过ajax调用从应用程序调用此Get方法: -

var source = {
                'id': 0,
                'Name': 'sagar'
            }            

            $.ajax({
                type: "GET",
                dataType: "json",
                url: "http://localhost:51366/api/Values",
                data: source,
                success: function (data) {
                    alert(data);
                },
                error: function (error) {

                    jsonValue = jQuery.parseJSON(error.responseText);
                    alert("error" + error.responseText);
                }
            });

调用方法但获得的SampleClass对象为null 但我已将id发送为0并将其命名为sagar。它应该检索这些值而不是null。

enter image description here

1 个答案:

答案 0 :(得分:3)

  1. 使用HttpPost标记服务器方法
  2. " POST"您的数据
  3. 在服务器上......

    [HttpPost]
    public string Get([FromBody]SampleClass sample)
    

    在客户端......

                $.ajax({
                    type: "POST",
                    dataType: "json",
                    url: "http://localhost:51366/api/Values",
                    data: source,
                    success: function (data) {
                        alert(data);
                    },
                    error: function (error) {
    
                        jsonValue = jQuery.parseJSON(error.responseText);
                        alert("error" + error.responseText);
                    }
                });
    

    编辑 - 不推荐:

    为了避免让身体进入" HttpGET"将数据发送到服务器将其放入查询字符串中,如下所示......

    $.ajax({
                        type: "GET",
                        dataType: "json",
                        url: "http://localhost:51366/api/Values?id=" + source.id + "&Name=" + source.Name,
                        success: function (data) {
                            alert(data);
                        },
                        error: function (error) {
    
                            jsonValue = jQuery.parseJSON(error.responseText);
                            alert("error" + error.responseText);
                        }
                    });