设计图:
数据库:
use master
go
if exists(select * from sys.databases where name='QU')
drop database QU
create database QU
use QU
create table class
(
classID int not null identity primary key,
classname varchar(10) not null
)
create table studentinfo
(
ID int not null identity primary key,
studentname varchar(10) not null,
age int not null,
phone varchar(50) not null,
email varchar(50) not null,
Fk_classID int references class(classID)
)
insert into class values('1班')
insert into class values('2班')
insert into class values('3班')
insert into studentinfo values('木子洋1',12,'12345678901','12345@qq.com',1)
insert into studentinfo values('木子洋2',13,'12345678902','12345@qq.com',2)
insert into studentinfo values('木子洋3',14,'12345678903','12345@qq.com',3)
insert into studentinfo values('木子洋4',15,'12345678904','12345@qq.com',1)
insert into studentinfo values('木子洋5',16,'12345678905','12345@qq.com',2)
select * from studentinfo
新建一个MVC项目,创建EF框架(代码student这个控制器里面)
写完控制器编写视图:
return view这句话选择view右键——添加视图——
视图名称:可以不修改
模板:查询(list)添加(create)修改(edit)
模型类:选择自己当前操作的实体类(比如我查询用到的实体类是student)
数据上下文类:不选
——点击确定
查询
需要根据要显示的内容显示在models写一个新的实体类
public class Student
{
public int ID { get; set; }
public string studentname { get; set; }
public int age { get; set; }
public string phone { get; set; }
public string email { get; set; }
public Nullable<int> Fk_classID { get; set; }
public string classname { get; set; }
}
控制器代码:
/// <summary>
/// 列表显示
/// </summary>
/// <returns></returns>
public ActionResult Index()
{
//实例化显示上下文
QUEntities db = new QUEntities();
var stu = new Student();
var model = db.studentinfo .Where(s => true).Select(s => new Student()
{
age = s.age,
Fk_classID = (int)s.Fk_classID,
classname = s.@class.classname,
email = s.email,
ID = s.ID,
phone = s.phone,
studentname = s.studentname,
}).ToList();
return View(model);
}
/// <summary>
/// 获取学员的班级信息
/// </summary>
/// <returns></returns>
private List<SelectListItem> GetClassInfo()
{
//1.实例化数据访问上下文
using (var db = new QUEntities())
{
//2.查询学员班级信息
//3.构造学员班级信息数据
var classInfo = db.@class.Where(c => true).Select(c => new SelectListItem
{
Text = c.classname,
Value = c.classID.ToString()
}).ToList();
return classInfo;
}
}
视图:
@model IEnumerable<WebApplication11.Models.Student>
<script src="~/Scripts/jquery-1.10.2.js"></script>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<h2>学员列表</h2>
<div class="form-group">
<label for="Name">姓名</label>
<input style="width:150px;" id="Name" name="Name" type="text">
<label for="Name">手机</label>
<input style="width:150px;" id="Name" name="Name" type="text">
<label for="Name">班级</label>
<select style="width:150px;height:25px;">
<option value="value">请选择</option>
</select>
<a href="@Url.Action("Add","Student")" class="btn btn-success">查询</a>
</div>
<table class="table">
<tr>
<td>编号</td>
<td>姓名</td>
<td>年龄</td>
<td>手机</td>
<td>邮箱</td>
<td>班级</td>
<td>操作</td>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.ID)
</td>
<td>
@Html.DisplayFor(modelItem => item.studentname)
</td>
<td>
@Html.DisplayFor(modelItem => item.age)
</td>
<td>
@Html.DisplayFor(modelItem => item.phone)
</td>
<td>
@Html.DisplayFor(modelItem => item.email)
</td>
<td>
@Html.DisplayFor(modelItem => item.classname)
</td>
<td>
<a href="@Url.Action("Edit","Student",new {id=item.ID })" class="btn btn-warning" style="margin-right: 10px;">修改</a>
<a href="javascript:;" onclick="deleteStudent(@item.ID)" class="btn btn-danger">删除</a>
</td>
</tr>
}
</table>
<a href="@Url.Action("Add","Student")" class="btn btn-success">添加</a>
@section Scripts
{
<script>
//删除学员
function deleteStudent(id) {
//如果确认删除则进行删除操作
if (confirm("确定要删除吗?")) {
//使用Ajax请求删除该记录
$.post("@Url.Action("Delete","Student")", { Id: id }, function (data) {
//如果执行成功则刷新页面重新进行数据绑定
if (data.IsSuccess) {
location.reload();
}
else {
alert(data.ErrorMessage);
}
}, "json");
}
}
</script>
}
添加
实体类:(studentadd)
public class studentadd
{
public int ID { get; set; }
/// <summary>
/// 姓名
/// </summary>
[DisplayName("姓名")]
[Required(ErrorMessage = "请输入姓名")]
[StringLength(4, ErrorMessage = "你的名字太长了,是火星来的么?")]
public string studentname { get; set; }
[DisplayName("年龄")]
[Required(ErrorMessage = "请输入年龄")]
[Range(0, 130, ErrorMessage = "您寿比南山,打破了吉尼斯记录,你造吗?")]
[RegularExpression(@"^\d{1,3}$", ErrorMessage = "您输入的格式不正确,请换个姿势再来一次")]
public int age { get; set; }
[DisplayName("手机")]
[Required(ErrorMessage = "请输入手机")]
[RegularExpression(@"^1[3578]\d{9}$", ErrorMessage = "您输入手机格式比较另类,无法与您取得联系~")]
public string phone { get; set; }
[DisplayName("邮箱")]
[Required(ErrorMessage = "请输入邮箱")]
[DataType(DataType.EmailAddress, ErrorMessage = "您输入的邮箱格式不正确~")]
public string email { get; set; }
/// <summary>
/// 班级Id
/// </summary>
[DisplayName("班级")]
[Required(ErrorMessage = "请选择班级")]
public Nullable<int> Fk_classID { get; set; }
}
控制器代码:(下拉框显示在查询里面)
/// <summary>
/// 添加学员
/// </summary>
/// <returns></returns>
public ActionResult Add()
{
var viewModel = new studentadd();
ViewBag.ClassInfo = GetClassInfo();
return View(viewModel);
}
/// <summary>
/// 提交添加新学员
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
[HttpPost]
public ActionResult Add(studentadd model)
{
//1.模型验证
if (ModelState.IsValid)
{
//2.如果验证通过,写入新数据
//2.1实例化数据访问上下文
using (var db = new QUEntities())
{
var entity = new studentinfo()
{
age = model.age,
Fk_classID = model.Fk_classID,
email = model.email,
phone = model.phone,
studentname = model.studentname
};
//2.2调用Add方法
db.studentinfo.Add(entity);
//2.3提交操作
db.SaveChanges();
ViewBag.Msg = "新学员添加成功!";
}
}
else
{ //3.如果验证不通过,消息提示
ModelState.AddModelError("", "您输入的信息有误!");
}
ViewBag.ClassInfo = GetClassInfo();
return View(model);
}
视图:
@model WebApplication11.Models.studentadd
@using (Html.BeginForm("Add", "Student", FormMethod.Post))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>添加学员</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.studentname, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.studentname, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.studentname, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.age, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.age, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.age, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.phone, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.phone, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.phone, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.email, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.email, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.email, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Fk_classID, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.Fk_classID, (List<SelectListItem>)ViewBag.ClassInfo, new { @class = "form-control" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="添加" class="btn btn-default" />
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<label style="color:red">@ViewBag.Msg</label>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
修改
实体类:(和添加是一个是一个实体类)
控制器:
#region 修改学员
/// <summary>
/// 修改学员
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public ActionResult Edit(int id)
{
//1.实例化数据访问上下文
using (var db = new QUEntities())
{
var viewModel = new studentadd();
//2.根据id查询对应的学员信息
var student = db.studentinfo.FirstOrDefault(s => s.ID == id);
if (student != null)
{
//3.构造视图需要的实体
viewModel = new studentadd()
{
age = student.age,
Fk_classID = (int)student.Fk_classID,
email = student.email,
ID = student.ID,
phone = student.phone,
studentname = student.studentname
};
}
ViewBag.ClassInfo = GetClassInfo();
return View(viewModel);
}
}
/// <summary>
/// 提交学员修改
/// </summary>
/// <param name="viewModel"></param>
/// <returns></returns>
[HttpPost]
public ActionResult Edit(studentadd viewModel)
{
//模型验证
if (ModelState.IsValid)
{
//1.实例化数据访问上下文
using (var db = new QUEntities())
{
//2.查询出当前修改的学员
var model = db.studentinfo.FirstOrDefault(s => s.ID == viewModel.ID);
//3.对学员的属性赋值
if (model != null)
{
model.age = viewModel.age;
model.Fk_classID = viewModel.Fk_classID;
model.email = viewModel.email;
model.phone = viewModel.phone;
model.studentname = viewModel.studentname;
//4.提交操作
db.SaveChanges();
ViewBag.Msg = "学员信息修改成功!";
}
}
}
else
{
ModelState.AddModelError("", "您输入的信息有误!");
}
ViewBag.ClassInfo = GetClassInfo();
return View(viewModel);
}
#endregion
视图:
@model WebApplication11.Models.studentadd
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>studentadd</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(model => model.ID)
<div class="form-group">
@Html.LabelFor(model => model.studentname, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.studentname, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.studentname, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.age, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.age, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.age, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.phone, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.phone, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.phone, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.email, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.email, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.email, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Fk_classID, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.Fk_classID, (List<SelectListItem>)ViewBag.ClassInfo, new { @class = "form-control" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="提交修改" class="btn btn-default" />
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<label style="color:red">@ViewBag.Msg</label>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
删除:(ajax)
实体类:(json)
/// <summary>
/// 返回结果消息json
/// </summary>
public class ResultModel
{
/// <summary>
/// 是否操作成功
/// </summary>
public bool IsSuccess { get; set; }
/// <summary>
/// 错误消息提示
/// </summary>
public string ErrorMessage { get; set; }
}
控制器:
/// <summary>
/// 删除学员
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpPost]
public ActionResult Delete(int id)
{
//1.实例化数据访问上下文
using (var db = new QUEntities())
{
var result = new ResultModel();
//2.查询当前删除的学员是否存在
var model = db.studentinfo.FirstOrDefault(s => s.ID == id);
if (model != null)
{
//3.如果存在则删除
//3.1调用Remove方法标记为删除
db.studentinfo.Remove(model);
//3.2提交操作
if (db.SaveChanges() > 0)
{
result.IsSuccess = true;
result.ErrorMessage = "删除成功";
}
else
{
result.IsSuccess = false;
result.ErrorMessage = "网络繁忙,请稍后重试";
}
}
else
{
//4.如果不存在则提示错误消息
result.IsSuccess = false;
result.ErrorMessage = "当前的学员已经删除!";
}
return Json(result);
}
}