1

I have this function in jQuery

var uri = "api/queries";

function test(){
    var params = {
        origin: $('#depair').val(),
        destination: $('#destair').val(),
        departure_date: $('#depdate').val(),
        currency: $('#currency').val(),
    }
    $.getJSON(uri, params)
        .done(function (data) {
            console.log(data);
    });
}

Which sends the request to this Controller:

public class QueriesController : ApiController
{
    [HttpGet]
    public string GetInfo()
    {
        return "blah";
    }
}

So, the request looks like this

http://localhost:55934/api/queries?origin=&destination=&departure_date=&currency=

How do I access the parameters of the request from inside the controller GetInfo method?

Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
Fisteon
  • 121
  • 2
  • 15

3 Answers3

4

You can include them as parameters to your function.

[HttpGet]
public string GetInfo(string origin, string destination, string departure_date, string currency)
{
    return "blah";
}
David Lee
  • 2,040
  • 17
  • 36
3
var origin = Request.QueryString["origin"];

Replacing "origin" with your parameter.

Ratatoskr
  • 189
  • 5
2

You can use Model Binding. First create a class (ViewModel) like this:

public class Querie
{
    public string Origin { get; set; }
    public string Destination { get; set; }
    public string Departure_date { get; set; }
    public string Currency { get; set; }
}

Then include this class as parameter to your method like this:

public class QueriesController : ApiController
{
    [HttpGet]
    public string GetInfo(Querie querie)
    {
        //querie.Origin
        return "blah";
    }
}

Model binding maps data from HTTP requests to action method parameters. The parameters may be simple types such as strings, integers, or floats, or they may be complex types. This is a great feature of MVC because mapping incoming data to a counterpart is an often repeated scenario, regardless of size or complexity of the data.

Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
  • @Fisteon If you are using Model Binding be sure to look into the Include function, `[Bind(Include = "Prop1,Prop2")]` . You would use this if you wanted to prevent certain parameters from being binding. This is good for security purposes. – David Lee Sep 14 '17 at 20:28
  • @DavidLee I think there is not need to use `Bind` since we have created a `ViewModel` class not using a domain class or business objects or entities and it already avoids *Mass Assignment* as you pointed. – Salah Akbari Sep 14 '17 at 20:36
  • @SAkbari agree with you there, just wanted to point it out in case he begins to use this in other areas of his project. – David Lee Sep 14 '17 at 20:37