1

I have an Angular 6 project. And I'm sending my request to .NET Core 2.1 Web API. I'm sending string fruit list like below. But, my data coming to C# has only one item like "'apple', 'orange', 'banana'" . But, I want three different strings. How can I achieve this? Please don't advice using "POST" method

Angular side

getFruitDetails() {
    let params = new HttpParams();
    params = params.append('fruitType', '35');
    params = params.append('fruits', JSON.stringify(['apple', 'orange', 'banana']));

    return this.http.get('https://localhost:5000/api/Fruit/GetFruitDetails', { params: params });
}

C# Side

public GetFruitDetails([FromQuery] FruitModel fruitModel)
{...}

public class FruitModel
{
    public int FruitType { get; set; }
    public List<string> Fruits { get; set; }
}
4
  • Why not using queryParams? Commented Dec 18, 2018 at 12:06
  • What is queryparams? When I googled, every results are HttpParams. @PardeepJain Commented Dec 18, 2018 at 12:08
  • Sending parameters using ? in url for example https://localhost:5000/api/Fruit/GetFruitDetails/?fruit1=apple&fruit2=banana... Commented Dec 18, 2018 at 12:10
  • 1
    Thanks a lot for reply @PardeepJain. I don't want concatting strings. So, I'm using HttpParams. MarcusHöglund' s solution is what I was looking for. Commented Dec 18, 2018 at 12:14

1 Answer 1

4

The FromQuery attribute will add all query params that matching fruits=value from the querystring into the list Fruits.

Therefore, compose the params as

getFruitDetails() {
    let params = new HttpParams();
    params = params.append('fruitType', '35');
    params = params.append('fruits', 'apple');
    params = params.append('fruits', 'orange');
    params = params.append('fruits', 'banana');

    return this.http.get('https://localhost:5000/api/Fruit/GetFruitDetails', { params: params });
}
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks a lot @MarcusHöglund . It worked. But, Is it common way or tricky way?
@HasanOzdemir its how the FromQuery attribute work. Its the standard way :)
@D-johnAnshani why should he do that? the FromQuery attribute solves this in an elegant way. Why bring more complexity to it by manually checking it
I think your way is not correct way @D-johnAnshani . Because, strings can have comma. And then that way gave wrong result.
You don't need to pass them one by one with params.append, you can add the array... just don't JSON.Stringify() it

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.