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?

3 Answers 3

5

You can include them as parameters to your function.

[HttpGet]
public string GetInfo(string origin, string destination, string departure_date, string currency)
{
    return "blah";
}
Sign up to request clarification or add additional context in comments.

Comments

3

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.

3 Comments

@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.
@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.
@SAkbari agree with you there, just wanted to point it out in case he begins to use this in other areas of his project.
3
var origin = Request.QueryString["origin"];

Replacing "origin" with your parameter.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.