ASP.NET MVC 标签绑定传值及后台获取并进行修改操作
先在aspx页面中引用对象,比如,我要修改teacher的相关信息,则引用edmx中创建的对象,代码如下:
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<EducationManage.Areas.BaseInfoManage.Models.Teachers>" %>
前台使用MVC标签进行绑定传值,代码如下:
<%:Html.TextBoxFor(t => t.name, new { id = "teacherModifyName", autocomplete = "off", style = "width:150px",maxLength = "16" })%>
//上面代码是绑定teacher表中的name字段
需要传什么值,即绑定该字段。
接下来在后台接收值,这是很关键的一步。
public ActionResult TeacherModify(Teachers teacherUpdate)
{
try
{
TeacherEntities teacherEntities = new TeacherEntities();
Teachers teachers = teacherEntities.teachers.SingleOrDefault(t => t.teacher_id == teacherUpdate.teacherId);
teacherUpdate.sex = "1"; //前台没有用标签绑定的字段需要自己赋值
teacherUpdate.state = "2"; //前台没有用标签绑定的字段需要自己赋值
//teachers.type = teacher.type;
//teachers.job_title = teacher.job_title;
//teachers.degree = teacher.degree;
//teachers.education = teacher.education;
//上面四行代码被我注释掉了,如果前台已经用MVC标签绑定,则不需要再重新赋值,MVC实体管理器会自动进行修改,这正是MVC的精妙
//可以减少很多代码量,这里只针对修改数据而言,增加另当别论
teacherEntities.ApplyCurrentValues("teachers", teacherUpdate); //这里的teacher对应数据库中的表名,不能写错
teacherEntities.SaveChanges();
需要特别说明的是teacherUpdate和teachers
teacherUpdate是从前台传过来的一个对象,而teachers是通过teacherUpdate的id查找出来的,这个步骤是必要的。
如果没有Teachers teachers = teacherEntities.teachers.SingleOrDefault(t => t.teacher_id == teacherUpdate.teacherId);这段代码,则在teacherEntities.ApplyCurrentValues("teachers", teacherUpdate);这个地方会出异常。切忌!
return View("~/Areas/BaseInfoManage/Views/FileUploadUpdateSuccess.aspx"); //最后再返回页面
}
catch
{
log.Error("修改教师信息失败");
return View("~/Areas/BaseInfoManage/Views/FileUploadUpdateError.aspx");
}
}