vgquotes/Src/VideoGameQuotes.Web/Controllers/CategoryController.cs
tmont ff3499b3b9 * edit/create/delete categories
* also made error views user-aware
2011-02-24 08:07:50 +00:00

78 lines
2.5 KiB
C#

using System.Web.Mvc;
using Portoa.Persistence;
using Portoa.Web.Controllers;
using VideoGameQuotes.Api;
using VideoGameQuotes.Web.Models;
using VideoGameQuotes.Web.Security;
using VideoGameQuotes.Web.Services;
namespace VideoGameQuotes.Web.Controllers {
public class CategoryController : Controller {
private readonly ICategoryService categoryService;
public CategoryController(ICategoryService categoryService) {
this.categoryService = categoryService;
}
[HttpPost, VerifyUser(Group = UserGroup.Admin)]
public JsonResult Delete(int id) {
if (id < 1) {
return Json(this.CreateJsonResponse("Invalid ID"));
}
try {
var category = categoryService.FindById(id);
var numQuotes = categoryService.GetQuotesForCategory(category);
if (numQuotes > 0) {
return Json(this.CreateJsonErrorResponse(
string.Format("There are {0} quotes that are still using this category", numQuotes)
));
}
} catch (EntityNotFoundException) {
return Json(this.CreateJsonErrorResponse("No category exists for ID " + id));
}
categoryService.Delete(id);
return Json(this.CreateJsonResponse());
}
[HttpPost, VerifyUser(Group = UserGroup.Admin)]
public JsonResult Edit(EditCategoryModel model) {
if (model.CategoryId < 1) {
ModelState.AddModelError("CategoryId", "Invalid category ID");
}
if (!ModelState.IsValid) {
return Json(this.CreateJsonErrorResponse("Some errors occurred"));
}
try {
var category = categoryService.FindById(model.CategoryId);
if (categoryService.FindByName(model.CategoryName) != null) {
return Json(this.CreateJsonErrorResponse("A category already exists for that name"));
}
category.Name = model.CategoryName;
category = categoryService.Save(category);
return Json(this.CreateJsonResponse(data: category.ToDto()));
} catch (EntityNotFoundException) {
return Json(this.CreateJsonErrorResponse("No category exists for ID " + model.CategoryId));
}
}
[HttpPost, VerifyUser]
public JsonResult Create(EditCategoryModel model) {
if (!ModelState.IsValid) {
return Json(this.CreateJsonErrorResponse("Some errors occurred."));
}
if (categoryService.FindByName(model.CategoryName) != null) {
return Json(this.CreateJsonErrorResponse("A category already exists for that name"));
}
var category = categoryService.Save(new Category { Name = model.CategoryName });
return Json(this.CreateJsonResponse(data: category.ToDto()));
}
}
}