MVC+SQL Server实现单表的增删查改
用vs2019+SQL Server2012实现1.打开VS2019选择Web应用程序,点击下一步。
2.选择MVC,点击创建。
MVC项目已经创建好了,我们来生成实体模型,先要在SQL中创建好库和表,这里就暂不作介绍了。
3.在Model中右击点击添加新建项,点击左边的数据,选中第一项,点击添加。
4.选择操作的数据库。
5.勾选操作的表。
6.成功后的界面如上所述。
下面就到了敲代码了,效果图如下。
控制器代码
public class StController : Controller
{
public StEntities db=new StEntities();
// GET: St
public ActionResult Index()
{
return View(db.S1.ToList());
}
public ActionResult Add()
{
return View();
}
[HttpPost]
public ActionResult Add(S1 s)
{
db.S1.Add(s);
db.SaveChanges();
return RedirectToAction("Index");
}
public ActionResult Delete(int id)
{
db.S1.Remove(db.S1.Find(id));
db.SaveChanges();
return RedirectToAction("Index");
}
public ActionResult Exit(int? id)
{
ViewBag.s = db.S1.Find(id);
return View();
}
[HttpPost]
public ActionResult Exit(S1 s)
{
db.Entry(s).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
}
视图代码
@{
ViewBag.Title = "Index";
}
@using Student.Models;
@model List<S1>
<h2>显示界面</h2>
<a href="/St/Add" class="btn btn-primary">添加学生</a>
<table class="table tab-content">
<tr>
<td>学生编号</td>
<td>学生姓名</td>
<td>学生年龄</td>
<td>操作</td>
</tr>
@foreach (var item in Model)
{
<tr>
<td>@item.StudentID</td>
<td>@item.StudentName</td>
<td>@item.StudentAge</td>
<td>
<a href="/St/Delete/@item.StudentID" class="btn btn-danger" onclick="return confirm('您确定要删除这个学生的信息吗?')">删除</a>
<a href="/St/Exit/@item.StudentID" class="btn btn-primary">编辑</a>
</td>
</tr>
}
</table>
@{
ViewBag.Title = "Add";
}
<h2>添加学生信息</h2>
<a href="/St/Index">返回首页</a>
<form action="/St/Add" method="post">
<label>学生姓名:</label>
<input type="text" name="StudentName" /><br />
<label>学生年龄:</label>
<input type="text" name="StudentAge" />
<input type="submit" value="提交"/>
</form>
@{
ViewBag.Title = "Exit";
}
@using Student.Models;
@{
S1 s = ViewBag.s;
}
<h2>修改学生信息</h2>
<a href="/St/Index">返回首页</a>
<form action="/St/Exit" method="post">
<input type="hidden" value="@s.StudentID" name="StudentID" />
<label>学生姓名:</label>
<input type="text" name="StudentName" value="@s.StudentName"/><br />
<label>学生年龄:</label>
<input type="text" name="StudentAge" value="@s.StudentAge"/>
<input type="submit" value="提交" />
</form>