Edna
Edna

Reputation: 132

AJAX GET REQUESTS

Please help, I'm stuck here. I have a problem with passing input parameter to my C# controller. I tried really a lot of things I found here, but still there's some mistake.

Here is code:

  var a = $.ajax({        
    type:"GET",
    url: "/Weather1/Weather_get",
    data: "location=Paris%",
    contentType: 'application/json; charset=utf-8',
    cache: false, 
    success: function (data) {
        console.log(data);
    }, //succes
    error: function (data) {
        console.log(data);
    }//error
}) //ajax;

And here is controller:

[HttpGet]
public JsonResult Weather_get(String  location) etc etc...

Everything I tried gives me input location NULL. I know my controller is working fine because I get data from it, but I really need that data to be for specific location, so that's why I need it like this. Also don't want to change it to POST because this is homework problem so I have to have both HttpPost and HttpGet in my controller.

Upvotes: 0

Views: 3045

Answers (4)

bRaNdOn
bRaNdOn

Reputation: 1082

just include the parameter name in your controller and the value you want to pass like this.

$.ajax({        
        type:"GET",
        url: '@Url.Action("Weather_get","Weather1")',
        data: { location:paris},
        dataType: 'json',
        cache: false, 
        success: function (data) {
            console.log(data);
        }, //succes
        error: function (data) {
            console.log(data);
        }//error
    }) //ajax;

Upvotes: 1

chrisarton
chrisarton

Reputation: 4441

You should probably use JSON.stringify.

something like this:

var data = {
   location: "Paris%"
};

var a = $.ajax({        
    type:"GET",
    url: "/Weather1/Weather_get",
    data: JSON.stringify(data),
    dataType: 'json',
    contentType: 'application/json',
    cache: false, 
    success: function (data) {
        console.log(data);
    }, //succes
    error: function (data) {
        console.log(data);
    }//error
}) //ajax;

Upvotes: 0

mkorman
mkorman

Reputation: 978

The way ASP.Net binds the HTTP request URL to the model used by your controller is controlled in part by the routing engine.

If you navigate to

/Weather1/Weather_get/Paris

do you see the data from Paris?

If so, you could modify your AJAX this way $.ajax({
type:"GET", url: "/Weather1/Weather_get/Paris" (etc.) })

Upvotes: 0

Amit
Amit

Reputation: 15387

Try this

 var place="Paris%";
 var a = $.ajax({        
    type:"GET",
    url: '@Url.Action("Weather_get","Weather1")',
    data: '{ "location":"' + place+ '"}',
    dataType: 'json',
    cache: false, 
    success: function (data) {
        console.log(data);
    }, //succes
    error: function (data) {
        console.log(data);
    }//error
}) //ajax;

Upvotes: 1

Related Questions