// GET: api/categories/{id} public IHttpActionResult GetCategoryById(int id) { var category = context.Categories.FirstOrDefault(c => c.Id == id); if (category == null) { return this.NotFound(); } CategoryViewModel categoryInfo = new CategoryViewModel(category); return this.Ok(categoryInfo); }
// GET: api/categories public IHttpActionResult GetCategories() { var categories = context.Categories; if (!categories.Any()) { return this.NotFound(); } var data = new List<CategoryViewModel>(); foreach (var category in categories) { CategoryViewModel cat = new CategoryViewModel(category); data.Add(cat); } return this.Ok(data); }
public IHttpActionResult PostCategory([FromBody]CategoryBindingModel model) { if (!ModelState.IsValid) { return this.BadRequest(this.ModelState); } var categoryExists = context.Categories.FirstOrDefault(c => c.Name == model.Name); if (categoryExists != null) { return this.BadRequest("Category already exists!"); } var categoryToAdd = new Category() { Name = model.Name }; context.Categories.Add(categoryToAdd); context.SaveChanges(); var data = new CategoryViewModel(categoryToAdd); return this.Ok(data); }