// PUT api/Posts/5 public HttpResponseMessage PutPost(int id, Post post) { if (!ModelState.IsValid) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState); } if (id != post.Id) { return Request.CreateResponse(HttpStatusCode.BadRequest); } db.Entry(post).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException ex) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex); } return Request.CreateResponse(HttpStatusCode.OK); }
public HttpResponseMessage PostPost(PostCreateModel model) { var post = new Post() { Title = model.Title, PostContent = model.PostContent, PostDate = model.PostDate, }; var categories = db.Categories.ToList(); var categoryNames = categories.Select(c => c.Name).ToList(); for (int i = 0; i < categoryNames.Count; i++) { if (model.Categories.Contains(categoryNames[i])) { post.Categories.Add(categories[i]); model.Categories.Remove(categoryNames[i]); } } foreach (var cat in model.Categories) { var category = new Category() { Name = cat }; post.Categories.Add(category); } db.Posts.Add(post); db.SaveChanges(); model.Id = post.Id; HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, model); response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = post.Id })); return response; }