Paolo B
Paolo B

Reputation: 3354

Adding to a Collection (List) via WebApi POST

I am trying to add favourites to a collection - List<Attraction> whenever a user clicks on a link for the desired Attraction.

My Api Controller is as follows:

public class FavouritesController : ApiController
{
    private List<Attraction> _favourites;

    private readonly IRepository _repo;

    public FavouritesController(IRepository repo)
    {
        _repo = repo;
    }

    public IEnumerable<Attraction> Get()
    {
        return _favourites;
    }

    [HttpPost]
    public IHttpActionResult Add(int id)
    {
        if (_favourites == null)
        {
            _favourites = new List<Attraction>();
        }

        var attraction = _repo.FindAttractionById(id);

        if (attraction == null)
        {
            return BadRequest();
        }

        _favourites.Add(attraction);

        return Ok();
    }

And this is my AngularJS Service:

function addToFavourites(id) {
    $http.post("/api/v1/favourites/" + id)
        .success(function(response) {
           //Success
        })

Then in the Angular controller for page:

$scope.addToFavourites = function() {
    dataService.addToFavourites(this.attraction.id);
    $scope.Favourites = dataService.getFavourites();
}

It works when I set breakpoint - but only adds one item to the collection - so if I click on the first item it adds the first item, but then if click on the second item it adds second item, but does not keep the first.

If I do a Get request in browser to localhost:xxxx/api/v1/favourites it just says null in window. How can I fix this and ensure state of the collection remains consistent?

Upvotes: 0

Views: 1517

Answers (1)

Win
Win

Reputation: 62260

First of all, HTTP is state less. It means every request is a new request, and List<Attraction> _favourites will always be null in your code.

If you want to persist the data, you want to keep it in persistent storage like database.

If you just want to test the API for the sake of testing, you can make static -

private static List<Attraction> _favourites;

Upvotes: 1

Related Questions