MVC test
1,index
@{
ViewBag.Title = "Index";
}
Index
| id | 姓名 | 状态 | 编辑 |
|---|---|---|---|
| @item.Id | @item.uName | @item.uMark | @Html.ActionLink("删除", "Del", new { id = item.Id }) @Html.ActionLink("修改", "Update", new { id = item.Id }) @Html.ActionLink("添加", "Add") |
2,添加视图
@model test.Models.tb_name
@{
ViewBag.Title = "Add";
}
Add
Create
@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
}
@Html.ActionLink("Back to List", "Index")
3,修改视图
@model test.Models.tb_name
@{
ViewBag.Title = "Update";
}
Modify
@using (Html.BeginForm("Update", "Index", FormMethod.Post))
{
| 修改:@Html.HiddenFor(a => a.Id) | |
| 课程名称 | @Html.DropDownListFor(a => a.Id, ViewBag.classList as IEnumerable |
| 学生姓名 | @Html.TextBoxFor(a => a.uName) |
| @Html.ActionLink("返回", "Index", "Index") | |
4,控制器
public class IndexController : Controller
{
testEntities db = new testEntities();
//
// GET: /Index/
public ActionResult Index()
{
testEntities db = new testEntities();
List list = (from d in db.tb_name select d).ToList();
ViewData["DataList"] = list;
return View();
}
/// 根据学生ID删除学生
///
/// 学生ID
///
[HttpGet]
public ActionResult Del(string id)
{
testEntities db = new testEntities();
int ids = Convert.ToInt32(id);
tb_name modelDel = new tb_name() { Id = ids };
db.tb_name.Attach(modelDel);
db.Entry(modelDel).State = System.Data.EntityState.Deleted;
db.SaveChanges();
return RedirectToAction("Index", "Index");
}
///
/// 根据学生编号修改学生
///
///
///
[HttpGet]
public ActionResult Update(string id)
{
int ids = Convert.ToInt32(id);
tb_name ts = (from a in db.tb_name where a.Id == ids select a).FirstOrDefault();
IEnumerable listItem = (from c in db.tb_name select c).ToList().Select(c => new SelectListItem { Value = c.Id.ToString(), Text = c.uName });
ViewBag.classList = listItem;
return View(ts);
}
[HttpPost]
///
/// 保存要修改的数据
///
/// 要修改的学生ID
///
public ActionResult Update(tb_name ts)
{
DbEntityEntry entry = db.Entry(ts);
entry.State = System.Data.EntityState.Unchanged;
entry.Property(a => a.uName).IsModified = true;
entry.Property(a => a.Id).IsModified = true;
db.SaveChanges();
return RedirectToAction("Index", "Index");
}
public ActionResult Add()
{
return View("Add");
}
///
/// 添加
///
///
[HttpPost]
public ActionResult Add(tb_name student)
{
try
{
if (ModelState.IsValid)
{
EntityState statebefore = db.Entry(student).State; //Detached
db.tb_name.Add(student);
EntityState stateAdd = db.Entry(student).State; //Added
db.SaveChanges();
EntityState stateafter = db.Entry(student).State;//Unchanged
return RedirectToAction("Index");
}
}
catch
{
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
}
return View(student);
}
}