摘要:MVC練習 新增刪除修改
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Mvc3test.Models;
namespace Mvc3test.Controllers
{
public class UserController : Controller
{
mvc3Entities1 DataBase=new mvc3Entities1();
//
// GET: /User/
public ActionResult Index()
{
List<User>list=DataBase.User.ToList();
return View(list);
}
//
// GET: /User/Details/5
public ActionResult Details(int id)
{
User record = DataBase.User.Where(m => m.User_ID == id).SingleOrDefault();
return View(record);
}
//
// GET: /User/Create
public ActionResult Create()
{
return View();
}
//
// POST: /User/Create
[HttpPost]
public ActionResult Create(FormCollection collection)
{
string User_Name = collection["User_Name"];
string User_Password = collection["User_Password"];
try
{
User record=new User();
record.User_Name=User_Name;
record.User_Password=User_Password;
DataBase.AddToUser(record);
DataBase.SaveChanges();
// TODO: Add insert logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
//
// GET: /User/Edit/5
public ActionResult Edit(int id)
{
User record = DataBase.User.Where(m => m.User_ID == id).SingleOrDefault();
return View(record);
}
//
// POST: /User/Edit/5
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
try
{
User record = DataBase.User.Where(m => m.User_ID == id).SingleOrDefault();
record.User_Name = collection["User_Name"];
record.User_Password = collection["User_Password"];
DataBase.SaveChanges();
// TODO: Add update logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
//
// GET: /User/Delete/5
[HttpGet]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
User record = DataBase.User.Where(m => m.User_ID == id).SingleOrDefault();
DataBase.User.DeleteObject(record);
DataBase.SaveChanges();
// TODO: Add delete logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
}