用数据绑定实现一个表单的数据添加和修改功能
整体内容继上一条MVC强类型:
MVC强类型
在ADD视图页面:
<body>
@using (Html.BeginForm("add", "home", FormMethod.Post))
{
<table>
<tr>
<td>编号:</td>
<td>@Html.TextBox("userid", "请填入用户编号")</td>
</tr>
<tr>
<td></td>
<td>@Html.TextBox("username", "请填入用户名称")</td>
</tr>
<tr>
<td></td>
<td>@Html.TextBox("userage", "请填入用户年龄")</td>
</tr>
<tr>
<td></td>
<td>@Html.TextBox("userphoto", "请填入用户照片")</td>
</tr>
</table>
<input type="submit" value="提交" class="btn btn-success">
}
</body>
在控制器里:
public ActionResult Add()
{
return View();
}
[HttpPost]//添加httppost特性的方法只能接受和处理POST方式传递过来的数据
public ActionResult Add(int userid,string username,int userage,string userphoto)
{
//数据添加的功能
User u = new User();
u.ID = userid;
u.Name = username;
u.Age = userage;
u.Photo = userphoto;
db.Entry(u).State = System.Data.Entity.EntityState.Added;
db.Users.Add(u);
db.SaveChanges();
return RedirectToAction("index");
编辑功能:
在index视图上:
<tbody>
@foreach (var item in Model)
{
<tr>
<td>@item.ID</td>
<td>@item.Name</td>
<td>@item.Age</td>
<td>@item.Photo</td>
<td>@Html.ActionLink("编辑","edit","home",new {uid=item.ID},new{@class="btn btn-danger"})</td>
</tr>
}
</tbody>
在控制器里:
public ActionResult edit()
{
//获取主页传递过来的id值,根据id查询对应记录
int id =Convert.ToInt32(Request["uid"]);
User u = db.Users.SingleOrDefault(t=>t.Id==id);
return View();
}
[HttpPost]
public ActionResult edit()
{
if(myfile != null)
{
myfile.SaveAs(Server.MapPath("~/images/"+myfile.FileName));
}
User u = new User();
u.Id = Id;
u.Name = Name;
u.Age = Age;
u.Photo = myfile.FileName;
db.Entry(u).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
return RedirectToAction("index");
}
在edit视图上:
<body>
@using (Html.BeginForm("add", "home", FormMethod.Post))
{
<table>
<tr>
<td>编号:</td>
<td>@Html.TextBoxFor(t=>t.Id)</td>
</tr>
<tr>
<td></td>
<td>@Html.TextBoxFor(t=>t.Name)</td>
</tr>
<tr>
<td></td>
<td>@Html.TextBoxFor(t=>t.Age)</td>
</tr>
<tr>
<td></td>
<td>@Html.TextBoxFor(t=>t.Photo)</td>
</tr>
</table>
<input type="submit" value="提交" class="btn btn-success">
}
</body>