一、Index主页(查询)
HomeController
MVCDemoEntities entity = new MVCDemoEntities();
public ActionResult Index()
{
var u = entity.Users.ToList(); ToList()是必备的,养成好这个习惯
return View(u);
}
Index.cshtml
@model IEnumerable<MVCDemo.Models.User>
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
@Html.ActionLink("新增", "Add")
<table>
<tr>
<th>Id</th>
<th>UserName</th>
<th>Age</th>
<th>Edit</th>
<th>Delete</th>
</tr>
@foreach (var u in Model)
{
<tr>
<td>@u.Id</td>
<td>@u.UserName</td>
<td>@u.Age</td>
<td>@Html.ActionLink("编辑", "Edit", new { id=u.Id})</td>
<td>@Html.ActionLink("删除", "Delete", new { id=u.Id})</td> Id作为参数传递,便于删除和修改时候的查询
</tr>
}
</table>
</div>
</body>
</html>
二、新增
HomeController
public ActionResult Add()
{
return View();
}
[HttpPost]
public ActionResult Add(User u)
{
User u1 = new User();
u1.UserName=Request["UserName"]; 从cshtml页面中获取值
u1.Age = Convert.ToInt32(Request["Age"]);
entity.Users.Add(u1);
entity.SaveChanges();
return RedirectToAction("Index");
}
Add.CShtml(使用的是模板)
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>User</legend>
<div class="editor-label">
@Html.LabelFor(model => model.UserName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.UserName)
@Html.ValidationMessageFor(model => model.UserName)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Age)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Age)
@Html.ValidationMessageFor(model => model.Age)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
三、修改
HomeController
[HttpGet]
public ActionResult Edit(int id)
{
//根据id查找对应的数据 然后展示
User user = entity.Users.FirstOrDefault(u => u.Id == id);
return View(user);
}
[HttpPost]
public ActionResult Edit()
{
int id =Convert.ToInt32( Request["userId"]);
User user = entity.Users.FirstOrDefault(u => u.Id == id);
user.UserName = Request["UserName"];
user.Age = Convert.ToInt32(Request["Age"]);
entity.SaveChanges();
return RedirectToAction("Index");
}
Edit.cshtml
<div>
@using (Html.BeginForm())
{
<table>
<tr>
<td>
@Html.LabelFor(model => model.UserName)
</td>
<td>
@Html.TextBox("UserName",Model.UserName)
</td>
</tr>
<tr>
<td>
@Html.LabelFor(model => model.Age)
</td>
<td>
@Html.TextBox("Age",Model.Age)
</td>
</tr>
<input type="hidden" name="userId" value="@Model.Id" />用隐藏的标签来存储Id
<input type="submit" name="name" value="提交" />
</table>
}
四、删除
HomeController
public ActionResult Delete(int id)
{
User user = entity.Users.FirstOrDefault(u => u.Id == id);
entity.Users.Remove(user);
entity.SaveChanges();
return RedirectToAction("Index");
}