// PUT api/Recipe/5 public HttpResponseMessage PutRecipe(int id, ViewModels.FlatRecipeViewModel recipe) { if (!ModelState.IsValid) { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState)); } if (id != recipe.Id) { return(Request.CreateResponse(HttpStatusCode.BadRequest)); } var r = db.Recipes.Find(id); if (r != null) { r.Name = recipe.Name; r.Ingredients.Clear(); foreach (var ingredientId in recipe.Ingredients.Split(',')) { int inid = 0; if (int.TryParse(ingredientId, out inid)) { var i = db.Ingredients.Find(inid); if (i != null) { r.Ingredients.Add(i); } } } } try { db.SaveChanges(); } catch (DbUpdateConcurrencyException ex) { return(Request.CreateErrorResponse(HttpStatusCode.NotFound, ex)); } return(Request.CreateResponse(HttpStatusCode.OK)); }
// POST api/Recipe public HttpResponseMessage PostRecipe(ViewModels.FlatRecipeViewModel recipe) { if (ModelState.IsValid) { var r = new Recipe { Name = recipe.Name, Created = DateTime.Now, Ingredients = new List <Ingredient>() }; foreach (var ingredientId in recipe.Ingredients.Split(',')) { int id = 0; if (int.TryParse(ingredientId, out id)) { var i = db.Ingredients.Find(id); if (i != null) { r.Ingredients.Add(i); } } } db.Recipes.Add(r); db.SaveChanges(); recipe.Id = r.Id; HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, recipe); response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = recipe.Id })); return(response); } else { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState)); } }