基于C#和ASP.NET MVC框架的增删改查(CRUD)示例
作为一个.NET后端开发人员(边缘),每天都是增删改查。。。所以下面这篇是我基于C#和ASP.NET MVC框架写的增删改查(CRUD)示例,使用SQL Server数据库。这个示例以一个简单的“学生信息管理系统”为例,包含学生的基本信息(如ID[学号]、姓名和年龄)。
1. 数据库设计
首先,创建一个名为StudentDB的数据库,并在其中创建一个Students表:
代码语言:javascript代码运行次数:0运行复制CREATE DATABASE StudentDB;
USE StudentDB;
CREATE TABLE Students
(
Id INT PRIMARY KEY IDENTITY(1,1),
Name NVARCHAR(50) NOT NULL,
Age INT NOT NULL
);
2. 创建ASP.NET MVC项目
在Visual Studio中创建一个新的ASP.NET MVC项目,选择“MVC”模板。
3. 配置数据库连接
在Web.config文件中添加数据库连接字符串:
代码语言:javascript代码运行次数:0运行复制<connectionStrings>
<add name="StudentDBContext" connectionString="Data Source=YOUR_SERVER_NAME;Initial Catalog=StudentDB;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
将YOUR_SERVER_NAME替换为你的SQL Server实例名称。
4. 创建Entity Framework模型
使用Entity Framework Code First方法。首先,安装Entity Framework NuGet包:
代码语言:javascript代码运行次数:0运行复制Install-Package EntityFramework
然后,在Models文件夹中创建一个Student类和StudentDBContext类: Models/Student.cs
代码语言:javascript代码运行次数:0运行复制using System.ComponentModel.DataAnnotations;
namespace StudentManagementSystem.Models
{
public class Student
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
}
Models/StudentDBContext.cs
代码语言:javascript代码运行次数:0运行复制using System.Data.Entity;
namespace StudentManagementSystem.Models
{
public class StudentDBContext : DbContext
{
public StudentDBContext() : base("StudentDBContext")
public DbSet<Student> Students { get; set; }
}
}
5. 创建控制器
在Controllers文件夹中创建一个StudentsController类: Controllers/StudentsController.cs
代码语言:javascript代码运行次数:0运行复制using System.Linq;
using System.Web.Mvc;
using StudentManagementSystem.Models;
namespace StudentManagementSystem.Controllers
{
public class StudentsController : Controller
{
private StudentDBContext db = new StudentDBContext();
// GET: Students
public ActionResult Index()
{
return View(db.Students.ToList());
}
// GET: Students/Create
public ActionResult Create()
{
return View();
}
// POST: Students/Create
[HttpPost]
public ActionResult Create(Student student)
{
if (ModelState.IsValid)
{
db.Students.Add(student);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(student);
}
// GET: Students/Edit/5
public ActionResult Edit(int id)
{
var student = db.Students.Find(id);
if (student == null)
{
return HttpNotFound();
}
return View(student);
}
// POST: Students/Edit/5
[HttpPost]
public ActionResult Edit(Student student)
{
if (ModelState.IsValid)
{
db.Entry(student).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(student);
}
// GET: Students/Delete/5
public ActionResult Delete(int id)
{
var student = db.Students.Find(id);
if (student == null)
{
return HttpNotFound();
}
return View(student);
}
// POST: Students/Delete/5
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(int id)
{
var student = db.Students.Find(id);
db.Students.Remove(student);
db.SaveChanges();
return RedirectToAction("Index");
}
}
}
6. 创建视图
在Views/Students文件夹中创建以下视图文件: Views/Students/Index.cshtml
代码语言:javascript代码运行次数:0运行复制@model IEnumerable<StudentManagementSystem.Models.Student>
<h2>Student List</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Age)
</th>
<th></th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Age)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
@Html.ActionLink("Delete", "Delete", new { id = item.Id })
</td>
</tr>
}
</table>
Views/Students/Create.cshtml
代码语言:javascript代码运行次数:0运行复制@model StudentManagementSystem.Models.Student
<h2>Create</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Student</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Name, "", 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
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。 原始发表:2025年02月24日,如有侵权请联系 cloudcommunity@tencent 删除c#mvcaspcrud框架
发布评论