C Sharper
C Sharper

Reputation: 8626

Send data to webapi GET Request Ajax call

I have below model class in webapi :-

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

Get method in Controller :-

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

I am calling this Get method from application through ajax call as:-

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

Method gets called but SampleClass object obtained is null But I have sent id as 0 and Name as sagar. It should retrieve these values instead null.

enter image description here

Upvotes: 0

Views: 15187

Answers (1)

War
War

Reputation: 8628

  1. Mark the server method with HttpPost
  2. "POST" your data

On the server ...

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

on the client ...

            $.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);
                }
            });

EDIT - Not Recommended:

To avoid the need for a body to allow you to "HttpGET" send the data to the server put it in the query string like this ...

$.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);
                    }
                });

Upvotes: 3

Related Questions