Advertisement
Guest User

Untitled

a guest
Dec 10th, 2016
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.98 KB | None | 0 0
  1. using SoftUniBlog.Models;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Data.Entity;
  5. using System.Linq;
  6. using System.Net;
  7. using System.Web;
  8. using System.Web.Mvc;
  9.  
  10. namespace SoftUniBlog.Controllers
  11. {
  12. public class CategoryController : Controller
  13. {
  14. // GET: Category
  15. public ActionResult Index()
  16. {
  17. return RedirectToAction("List");
  18. }
  19.  
  20. public ActionResult List()
  21. {
  22. using (var database = new BlogDbContext())
  23. {
  24. var categories = database.Categories
  25. .ToList();
  26.  
  27. return View(categories);
  28. }
  29. }
  30.  
  31. public ActionResult Create()
  32. {
  33. return View();
  34. }
  35.  
  36. [HttpPost]
  37. public ActionResult Create(Category category)
  38. {
  39. if (ModelState.IsValid)
  40. {
  41. using (var database = new BlogDbContext())
  42. {
  43. database.Categories.Add(category);
  44. database.SaveChanges();
  45.  
  46. return RedirectToAction("Index");
  47. }
  48. }
  49. return View(category);
  50. }
  51.  
  52. public ActionResult Edit(int? id)
  53. {
  54. if (id == null)
  55. {
  56. return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
  57. }
  58.  
  59. using (var database = new BlogDbContext())
  60. {
  61. var category = database.Categories
  62. .FirstOrDefault(c => c.Id == id);
  63.  
  64. if (category == null)
  65. {
  66. return HttpNotFound();
  67. }
  68.  
  69. return View(category);
  70. }
  71. }
  72.  
  73. // GET: Category/Edit
  74. [HttpPost]
  75. public ActionResult Edit(Category category)
  76. {
  77. if (ModelState.IsValid)
  78. {
  79. using (var database = new BlogDbContext())
  80. {
  81. database.Entry(category).State = System.Data.Entity.EntityState.Modified;
  82. database.SaveChanges();
  83.  
  84. return RedirectToAction("Index");
  85. }
  86. }
  87. return View(category);
  88. }
  89.  
  90.  
  91.  
  92. //POST: Category/Delete
  93. [HttpPost]
  94. [ActionName("Delete")]
  95. public ActionResult DeleteConfirmed(int? id)
  96. {
  97. using (var database = new BlogDbContext())
  98. {
  99. var category = database.Categories.FirstOrDefault(c => c.Id == id);
  100. var categoryArticles = category.Articles.ToList();
  101.  
  102. foreach (var article in categoryArticles)
  103. {
  104. database.Articles.Remove(article);
  105. }
  106.  
  107. database.Categories.Remove(category);
  108. database.SaveChanges();
  109.  
  110. return RedirectToAction("Index");
  111. }
  112. }
  113. }
  114. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement