コード例 #1
0
        //public IActionResult Post([FromBody]Trip theTrip)
        public async Task <IActionResult> Post([FromBody] TripViewModel theTrip)
        {
            if (ModelState.IsValid)
            {
                // TODO: Save Trip not TripViewModel to database!
                // LET'S USE AUTOMAPPER INSTEAD!!! (NuGet package defined in project.json)
                //var newTrip = new Trip()
                //{
                //    Name = theTrip.Name,
                //    DateCreated = theTrip.Created
                //};
                var newTrip = Mapper.Map <Trip>(theTrip);
                newTrip.UserName = User.Identity.Name;

                // Save new trip to database
                _repository.AddTrip(newTrip);
                if (await _repository.SaveChangesAsync())
                {
                    //return Created($"api/trips/{theTrip.Name}", newTrip); // <- using newTrip (Trip) instead of theTrip (TripViewModel)
                    return(Created($"api/trips/{theTrip.Name}", Mapper.Map <TripViewModel>(newTrip))); // <- Returning TripViewModel instead of exposing Trip
                }
            }

            //return Ok(true);
            //return BadRequest("Bad data!");
            return(BadRequest("Failed to save the trip!"));
        }
コード例 #2
0
        public async Task <IActionResult> Post([FromBody] TripViewModel theTrip)
        {
            if (ModelState.IsValid)
            {
                // save to Database
                var newTrip = Mapper.Map <Trip>(theTrip);
                _repository.AddTrip(newTrip);

                if (await _repository.SaveChangesAsync())
                {
                    return(Created($"api/trips/{theTrip.Name}", Mapper.Map <TripViewModel>(newTrip)));
                }
            }
            return(BadRequest("Failed to save the trip!"));
        }