欢迎来到飞鸟慕鱼博客,开始您的技术之旅!
当前位置: 首页知识笔记正文

实现投票系统的MVC3实体框架(二)在

墨初 知识笔记 108阅读

,的最后一节我们在实体Frmaework模型中添加了模型。接下来,我们需要完成控制层的编码:1。右键构建控制器目录,添加一个控制器:2 .添加一个家庭控制器:3。添加一个管理控制器:4。创建后,下面两个。cs文件将被添加到控制器目录:5。五号房的密码。HomeControllers.cs如下:公共类home controller : controller {//get 3360/home/public action result Index(){ Models。VoteEntities mv=新型号。voteen tities();//创建实体对象返回视图(mv。users . to list());//将查询结果输出到视图层}} 6。admincontrollers.cs中的代码如下:公共类admin controller : controller {//get 3360/admin/public action result index(){ models。投票实体mv=新模型。投票实体();//创建数据实体

pan>
  • List<Models.Users> list = mv.Users.ToList(); //得到users表中所有信息
  • ViewModel.List = list; //将表中信息赋值给ViewModel.List,注意List为动态表达式,是自命名的。
  • return View();
  • }
  • //
  • // GET: /Admin/Details/5
  • public ActionResult Details(int id)
  • {
  • return View();
  • }
  • //
  • // GET: /Admin/Create
  • public ActionResult Create()
  • {
  • return View();
  • }
  • //
  • // POST: /Admin/Create
  • [HttpPost]
  • public ActionResult Create(Models.Users mu)
  • {
  • try
  • {
  • string picname = Path.Get(Request.Files["up"].);//得到文件的名字
  • string = Server.MapPath("/Content/") + picname; //得到要保存在服务器上的路径
  • Request.Files["up"].SaveAs();
  • mu.UserPicPath = picname; //在数据加保存文件的相对路径(文件名称)就可以了
  • Models.VoteEntities mv = new Models.VoteEntities();
  • mv.AddToUsers(mu);
  • mv.SaveChanges();
  • return RedirectToAction("Index");
  • }
  • catch
  • {
  • return View();
  • }
  • }
  • //
  • // GET: /Admin/Edit/5
  • public ActionResult Edit(int id)
  • {
  • return View();
  • }
  • //
  • // POST: /Admin/Edit/5
  • [HttpPost]
  • public ActionResult Edit(int id, Models.Users mu)
  • {
  • try
  • {
  • Models.VoteEntities mv = new Models.VoteEntities();
  • mv.Users.Single(m => m.id == id).UserName = mu.UserName; //查询出指定用户名并更新为新用户
  • mv.Users.Single(m => m.id == id).VoteCount = mu.VoteCount; //查询出指定票数并更新为新票数
  • mv.SaveChanges(); //保存更改
  • return RedirectToAction("Index");
  • }
  • catch
  • {
  • return View();
  • }
  • }
  • //
  • // GET: /Admin/Delete/5
  • public ActionResult Delete(int id)
  • {
  • Models.VoteEntities mv = new Models.VoteEntities();
  • mv.DeleteObject(mv.Users.Single(m => m.id == id));//查询出指定ID的唯一值并执行删除操作
  • mv.SaveChanges();
  • return RedirectToAction("Index");
  • }
  • // POST: /Admin/Delete/5
  • [HttpPost]
  • public ActionResult Delete(int id, FormCollection collection)
  • {
  • try
  • {
  • return RedirectToAction("Index");
  • }
  • catch
  • {
  • return View();
  • }
  • }
  • }
  • 以上为两个控制器类中的代码,下一节,我们为控制器添加指定的视图层界面。

    未完待续......

    标签:
    声明:无特别说明,转载请标明本文来源!