(一)主页面显示 代码
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using MvcApplication1.Models; namespace MvcApplication1.Controllers { public class HomeController : Controller { // // GET: /Home/ //主页视图 public ActionResult Index() { List<student> list = new StudentDA().Select(); // ViewBag.stu = new StudentDA().Select(); return View(list); } //修改页面视图 public ActionResult xiugai(string id) { // ViewBag.data = new StudentDA().Select(id); student list = new StudentDA().Select(id); return View(list); } //更新修改按钮动作 public ActionResult Update(string sno, string sname, string ssex, DateTime sbirthday, string class1) { try { new StudentDA().Update(sno, sname, ssex, sbirthday, class1); return RedirectToAction("Index"); } catch (Exception) { return RedirectToAction("chucuo", "Home"); } } //删除动作 public ActionResult Delete(string id) { try { new StudentDA().Delete(id); return RedirectToAction("Index"); } catch (Exception) { return RedirectToAction("Decuowu", "Home"); } } //增加页面视图 public ActionResult zengjia() { student a = new student(); return View(a); } //添加按钮动作 public ActionResult ADD(student a) { try { new StudentDA().Insert( a); return RedirectToAction("Index"); } catch (Exception) { return RedirectToAction("chucuo","Home"); } } //错误页面视图 public ActionResult chucuo() { return View(); } //删除错误页面视图 public ActionResult Decuowu() { return View(); } //回到主页按钮动作 public ActionResult tiaozhuan() { return RedirectToAction("Index"); } } }
(二)往数据库里添加方法
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace MvcApplication1.Models { public class StudentDA { private MyDbDataContext Context = new MyDbDataContext(); //查询学生信息 public List<student> Select() { return Context.student.ToList(); } //按学号查询单个学生信息 public student Select(string sno) { var query = Context.student.Where(p=>p.Sno==sno); if (query.Count()>0) { return query.First(); } return null; } //插入增加数据库 public void Insert(student a) { Context.student.InsertOnSubmit(a); Context.SubmitChanges(); } //删除 public void Delete(string sno) { var query = Context.student.Where(p=>p.Sno==sno); if (query.Count()>0) { student stu = query.First(); Context.student.DeleteOnSubmit(stu); Context.SubmitChanges(); } } //修改 public void Update(string sno, string sname, string ssex, DateTime sbirthday, string class1) { var query = Context.student.Where(p => p.Sno == sno); if (query.Count() > 0) { student stu = query.First(); stu.Sname = sname; stu.Ssex = ssex; stu.Sbirthday = sbirthday; stu.Class = class1; Context.SubmitChanges(); } } } }