MVC3+Entity Framework 实现投票系统(二)

来源:互联网 发布:海南广电网络 编辑:程序博客网 时间:2024/05/17 06:56

上一节,我们将Models加入了实体对象模型(Entity Frmaework模型)接下来我们要完成控制层的代码编写:

1.在Controllers(控制器)目录点右建,添加一个控制器:

2.添加Home控制器:

3.添加Admin控制器:

4.创建完成后,在Controllers目录中会增加以下两个.cs文件:

5.HomeControllers.cs中的代码如下:

  1. public class HomeController : Controller
  2. {
  3. //
  4. // GET: /Home/
  5. public ActionResult Index()
  6. {
  7. Models.VoteEntities mv = new Models.VoteEntities();//创建实体对象
  8. return View(mv.Users.ToList()); //将查询结果向视图层输出
  9. }
  10. }

6.AdminControllers.cs中代码如下:

  1. public class AdminController : Controller
  2. {
  3. //
  4. // GET: /Admin/
  5. public ActionResult Index()
  6. {
  7. Models.VoteEntities mv = new Models.VoteEntities(); //创建数据实体
  8. List<Models.Users> list = mv.Users.ToList(); //得到users表中所有信息
  9. ViewModel.List = list; //将表中信息赋值给ViewModel.List,注意List为动态表达式,是自命名的。
  10. return View();
  11. }
  12. //
  13. // GET: /Admin/Details/5
  14. public ActionResult Details(int id)
  15. {
  16. return View();
  17. }
  18. //
  19. // GET: /Admin/Create
  20. public ActionResult Create()
  21. {
  22. return View();
  23. }
  24. //
  25. // POST: /Admin/Create
  26. [HttpPost]
  27. public ActionResult Create(Models.Users mu)
  28. {
  29. try
  30. {
  31. string picname = Path.GetFileName(Request.Files["up"].FileName);//得到文件的名字
  32. string filepath = Server.MapPath("/Content/") + picname; //得到要保存在服务器上的路径
  33. Request.Files["up"].SaveAs(filepath);
  34. mu.UserPicPath = picname; //在数据加保存文件的相对路径(文件名称)就可以了
  35. Models.VoteEntities mv = new Models.VoteEntities();
  36. mv.AddToUsers(mu);
  37. mv.SaveChanges();
  38. return RedirectToAction("Index");
  39. }
  40. catch
  41. {
  42. return View();
  43. }
  44. }
  45. //
  46. // GET: /Admin/Edit/5
  47. public ActionResult Edit(int id)
  48. {
  49. return View();
  50. }
  51. //
  52. // POST: /Admin/Edit/5
  53. [HttpPost]
  54. public ActionResult Edit(int id, Models.Users mu)
  55. {
  56. try
  57. {
  58. Models.VoteEntities mv = new Models.VoteEntities();
  59. mv.Users.Single(m => m.id == id).UserName = mu.UserName; //查询出指定用户名并更新为新用户
  60. mv.Users.Single(m => m.id == id).VoteCount = mu.VoteCount; //查询出指定票数并更新为新票数
  61. mv.SaveChanges(); //保存更改
  62. return RedirectToAction("Index");
  63. }
  64. catch
  65. {
  66. return View();
  67. }
  68. }
  69. //
  70. // GET: /Admin/Delete/5
  71. public ActionResult Delete(int id)
  72. {
  73. Models.VoteEntities mv = new Models.VoteEntities();
  74. mv.DeleteObject(mv.Users.Single(m => m.id == id));//查询出指定ID的唯一值并执行删除操作
  75. mv.SaveChanges();
  76. return RedirectToAction("Index");
  77. }
  78. // POST: /Admin/Delete/5
  79. [HttpPost]
  80. public ActionResult Delete(int id, FormCollection collection)
  81. {
  82. try
  83. {
  84. return RedirectToAction("Index");
  85. }
  86. catch
  87. {
  88. return View();
  89. }
  90. }
  91. }

以上为两个控制器类中的代码,下一节,我们为控制器添加指定的视图层界面。

未完待续......