C#利用ASP.NET Core开发学生管理系统详解

这里是C#利用ASP.NET Core开发学生管理系统的完整攻略。

步骤一:创建.NET Core Web应用程序

  1. 打开Visual Studio,并以管理员身份运行。
  2. 在Visual Studio中选择“文件”>“新建”>“项目”。
  3. 选择".NET Core"类别,然后选择“ASP.NET Core Web应用程序”模板(或“ASP.NET Core Web应用程序(模型-视图-控制器)”模板)
  4. 为项目命名,并选择合适的位置。
  5. 选择“Web应用程序(.NET Core)”模板,并确保在“身份验证”下选择“无身份验证”。
  6. 创建项目后,可以在文件夹树中看到多个默认文件,包括Controllers和Views文件夹,Startup.cs和Program.cs文件以及wwwroot静态文件夹。

步骤二:连接数据库

  1. 在Visual Studio的“工具”选项中打开“NuGet包管理器控制台”。
  2. 在“包管理器控制台”窗口中,键入以下命令来安装Microsoft.EntityFrameworkCore.Tools包:
Install-Package Microsoft.EntityFrameworkCore.Tools
  1. 随后,安装需要与数据库进行通信的数据库提供程序软件包,如Microsoft.EntityFrameworkCore.SqlServer。
Install-Package Microsoft.EntityFrameworkCore.SqlServer
  1. 在项目文件夹中创建名为“Data”的新文件夹。
  2. 在“Data”文件夹中创建以下上下文类:
using Microsoft.EntityFrameworkCore;
namespace StudentManagementSystem.Models{
public class AppDbContext : DbContext
{
    public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
    {
    }
    public DbSet<Student> Students { get; set; }
}
}
  1. 打开Startup.cs文件并替换ConfigureServices()方法的代码:
public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContextPool<AppDbContext>(options =>
    options.UseSqlServer(Configuration.GetConnectionString("StudentDBConnection")));
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}

步骤三:创建Model

  1. 在Models文件夹中创建一个名为Student.cs的新类。
namespace StudentManagementSystem.Models{
    public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public Gender? Gender { get; set; }
        public string Email { get; set; }
        public string PhotoPath { get; set; }
    }
}
  1. 请注意,此类遵循“单个职责原则”,并且只包含与学生相关的信息。

步骤四:创建控制器和视图

  1. 在Controllers文件夹中创建一个名为StudentController.cs的新类。
using Microsoft.AspNetCore.Mvc;
using StudentManagementSystem.Models;
using System.Linq;
namespace StudentManagementSystem.Controllers{
public class StudentController : Controller
{
    private readonly AppDbContext _context;
    public StudentController(AppDbContext context)
    {
        _context = context;
    }
    public IActionResult Index()
    {
        var students = _context.Students.ToList();
        return View(students);
    }
 }
}
  1. 创建“Views”文件夹,然后在该文件夹中创建名为“Student”的新文件夹。
  2. 在“Student”文件夹中创建“Index.cshtml”视图。
@model IEnumerable<StudentManagementSystem.Models.Student>
@{
    ViewData["Title"] = "Index";
}
<table class="table">
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.Name)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Gender)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Email)
            </th>
        </tr>
    </thead>
    <tbody>
        @foreach (var student in Model)
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => student.Name)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => student.Gender)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => student.Email)
                </td>
            </tr>
        }
    </tbody>
</table>
  1. 启动应用程序,然后导航到“https://localhost:44355/Student/Index”以查看学生信息。

示例一:插入数据

以添加一个新学生的过程为例子:

1.在StartUp.cs里面添加头文件:

using StudentManagementSystem.ViewModels;

2.在Models文件夹里面,创建一个新文件夹ViewModels,在该文件夹下创建一个新的类StudentCreateViewModel.cs:

using System.ComponentModel.DataAnnotations;
using StudentManagementSystem.Models;
namespace StudentManagementSystem.ViewModels
{
    public class StudentCreateViewModel
    {
        [Required(ErrorMessage = "请填写名字")]
        [MaxLength(50, ErrorMessage = "名字长度不能超过50个字符")]
        public string Name { get; set; }
        [Required]
        public Gender? Gender { get; set; }
        [Required(ErrorMessage = "请填写电子邮件地址")]
        [EmailAddress(ErrorMessage = "请填写正确的电子邮件地址")]
        public string Email { get; set; }
        public string PhotoPath { get; set; }
    }
}

3.修改StudentController.cs:

public class StudentController : Controller
{
    private readonly AppDbContext _context;
    public StudentController(AppDbContext context)
    {
        _context = context;
    }
    public IActionResult Index()
    {
        var students = _context.Students.ToList();
        return View(students);
    }
    public IActionResult Create()
    {
        return View();
    }
    [HttpPost]
    public IActionResult Create(StudentCreateViewModel model)
    {
        if (ModelState.IsValid)
        {
            var student = new Student
            {
                Name = model.Name,
                Gender = model.Gender,
                Email = model.Email,
                PhotoPath = model.PhotoPath
            };
            _context.Students.Add(student);
            _context.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(model);
    }
}
public IActionResult Create(StudentCreateViewModel model)
{
    if (ModelState.IsValid)
    {
        var student = new Student
        {
            Name = model.Name,
            Gender = model.Gender,
            Email = model.Email,
            PhotoPath = model.PhotoPath
        };
        _context.Students.Add(student);
        _context.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(model);
}

4.修改Views/Student中的Create.cshtml:

@model StudentManagementSystem.ViewModels.StudentCreateViewModel
@{
    ViewData["Title"] = "Create";
}
<h2>Create</h2>
<form asp-action="Create" enctype="multipart/form-data">
    <div asp-validation-summary="ModelOnly" class="text-danger"></div>
    <div class="form-group">
        <label asp-for="Name" class="control-label"></label>
        <input asp-for="Name" class="form-control" />
        <span asp-validation-for="Name" class="text-danger"></span>
    </div>
    <div class="form-group">
        <label asp-for="Gender" class="control-label"></label>
        <select asp-for="Gender" class="form-control">
            <option value="">---请选择性别---</option>
            <option value="0">女</option>
            <option value="1">男</option>
        </select>
        <span asp-validation-for="Gender" class="text-danger"></span>
    </div>
    <div class="form-group">
        <label asp-for="Email" class="control-label"></label>
        <input asp-for="Email" class="form-control" />
        <span asp-validation-for="Email" class="text-danger"></span>
    </div>
    <div class="form-group">
        <label asp-for="PhotoPath" class="control-label"></label>
        <input asp-for="PhotoPath" type="file" />
        <span asp-validation-for="PhotoPath" class="text-danger"></span>
    </div>
    <div class="form-group">
        <input type="submit" value="Create" class="btn btn-primary" />
    </div>
</form>
<div>
    <a asp-action="Index">Back to List</a>
</div>

5.访问https://localhost:44355/Student/Create,可以显示表单;在必填项中填入信息,提交表单后数据有效性检查结果正确,数据被插入。

示例二:编辑和删除数据

以编辑和删除学生信息为例:

1.在Views/Student中的Index.cshtml中添加编辑和删除按钮:

<td>
    <a asp-action="Edit" asp-route-id="@student.Id">编辑</a>
    <a asp-action="Delete" asp-route-id="@student.Id" class="btn btn-danger"
       onclick="return confirm('Are you sure to delete?')">删除</a>
</td>

2.在StudentController.cs添加Edit()方法:

public IActionResult Edit(int id)
{
    var student = _context.Students.Find(id);
    if (student == null)
    {
        return NotFound();
    }
    var studentEditViewModel = new StudentEditViewModel
    {
        Id = student.Id,
        Name = student.Name,
        Gender = student.Gender,
        Email = student.Email,
        ExistingPhotoPath = student.PhotoPath
    };
    return View(studentEditViewModel);
}

3.在ViewModels文件夹中创建StudentEditViewModel.cs:

using StudentManagementSystem.Models;
namespace StudentManagementSystem.ViewModels
{
    public class StudentEditViewModel : StudentCreateViewModel
    {
        public int Id { get; set; }
        public string ExistingPhotoPath { get; set; }
    }
}

4.修改Views/Student中的Edit.cshtml:

@model StudentManagementSystem.ViewModels.StudentEditViewModel
@{
    ViewData["Title"] = "Edit";
}
<h2>Edit</h2>
<form asp-action="Edit">
    @Html.HiddenFor(model => model.Id)
    <div asp-validation-summary="ModelOnly" class="text-danger"></div>
    <div class="form-group">
        <label asp-for="Name" class="control-label"></label>
        <input asp-for="Name" class="form-control" />
        <span asp-validation-for="Name" class="text-danger"></span>
    </div>
    <div class="form-group">
        <label asp-for="Gender" class="control-label"></label>
        <select asp-for="Gender" class="form-control">
            <option value="">---请选择性别---</option>
            <option value="0">女</option>
            <option value="1">男</option>
        </select>
        <span asp-validation-for="Gender" class="text-danger"></span>
    </div>
    <div class="form-group">
        <label asp-for="Email" class="control-label"></label>
        <input asp-for="Email" class="form-control" />
        <span asp-validation-for="Email" class="text-danger"></span>
    </div>
    <div class="form-group">
        <input type="hidden" asp-for="ExistingPhotoPath" />
        <label asp-for="PhotoPath" class="control-label"></label>
        <input asp-for="PhotoPath" class="form-control" />
        <span asp-validation-for="PhotoPath" class="text-danger"></span>
    </div>
    <div class="form-group">
        <img src="@Model.ExistingPhotoPath" alt="个人照片" style="max-height: 200px" />
    </div>
    <div class="form-group">
        <input type="submit" value="提交" class="btn btn-primary" />
    </div>
</form>
<div>
    <a asp-action="Index">返回</a>
</div>

5.在StudentController.cs添加Edit()方法中添加相应的HttpPost方法:

[HttpPost]
public IActionResult Edit(StudentEditViewModel model)
{
    if (ModelState.IsValid)
    {
        var student = _context.Students.Find(model.Id);
        if (student == null)
        {
            return NotFound();
        }
        student.Name = model.Name;
        student.Gender = model.Gender;
        student.Email = model.Email;
        student.PhotoPath = model.PhotoPath;
        _context.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(model);
}

6.添加Delete()方法:

public IActionResult Delete(int id)
{
    var student = _context.Students.Find(id);
    if (student == null)
    {
        return NotFound();
    }
    _context.Students.Remove(student);
    _context.SaveChanges();
    return RedirectToAction("Index");
}

7.访问https://localhost:44355/Student/Index,可以看到每个学生条目后面都有一个编辑和删除链接。点击“编辑”链接会打开编辑页并显示学生信息。在编辑页上提交表单后,数据已被更新。点击“删除”链接将删除相应的学生信息。

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:C#利用ASP.NET Core开发学生管理系统详解 - Python技术站

(0)
上一篇 2023年6月3日
下一篇 2023年6月3日

相关文章

  • C#编程实现QQ界面的方法

    C#编程实现QQ界面的方法 前言 QQ是中国最流行的即时通讯软件之一,它的界面十分经典,因此,很多初学编程的人都想尝试使用C#编写一个类似QQ的界面。本文将介绍如何使用C#编写QQ界面的方法,并提供两个示例说明。 第一步:界面设计 在C#中,我们可以使用Visual Studio中的Windows Form进行界面的设计。因此,第一步就是打开Visual S…

    C# 2023年5月31日
    00
  • 如何通过C#/VB.NET 代码调整PDF文档的页边距

    PDF边距是页面主要内容区域和页面边缘之间的距离。与Word页边距不同,PDF文档的页边距很难更改。因为Adobe没有提供操作页边距的直接方法。但是,您可以通过缩放页面内容来改变页边距。本文将介绍如何在不更改页面大小的情况下使用C#/VB.NET 代码调整PDF文档的页边距。 增加PDF文档的页边距 缩短PDF文档的页边距 增加PDF文档的页边距 扩大PDF…

    C# 2023年4月27日
    00
  • C#中流的使用和分类

    C#中流的使用和分类 在C#中,流(Stream)是个非常重要的概念,它是数据的一个序列,可以被读取或写入。本文将介绍C#中流的使用和分类。 流的分类 在C#中,流根据数据传输的方向和方式可以分为以下几种: 输入流:从外部设备或其它源读取数据并传输到程序中。 输出流:从程序中将数据传输到外部设备或其它目标。 内存流:将数据存储在内存中的流,数据不是来自外部设…

    C# 2023年5月15日
    00
  • C# WinForm窗体编程中处理数字的正确操作方法

    处理数字在C# WinForm窗体编程中是非常常见的任务。为了确保处理数字的准确性和避免常见的错误,我们应该采用一些正确的操作方法。下面是一些在C# WinForm窗体编程中处理数字的正确操作方法的完整攻略。 1. 使用数据类型正确 在处理数字时,我们应该使用正确的数据类型。C#中有多种数据类型可用于处理数字,例如int、float、double等。如果我们…

    C# 2023年6月6日
    00
  • 两种获取connectionString的方式案例详解

    下面是“两种获取connectionString的方式案例详解”的完整攻略: 概述 在使用ASP.NET的开发中,我们常常需要连接数据库,在连接数据库时,需要首先获取连接字符串。获取连接字符串的方式有很多种,本文将介绍两种常用的方式,分别是: 通过web.config文件获取连接字符串 通过代码获取连接字符串 通过web.config文件获取连接字符串 在A…

    C# 2023年5月31日
    00
  • Unity3D摄像机跟随小球移动而不旋转的设置方法

    让我们来讲解一下“Unity3D摄像机跟随小球移动而不旋转的设置方法”,以下是具体的步骤: 步骤一:创建一个场景 首先,在Unity编辑器中创建一个新场景,然后创建一个小球和一个摄像机。将小球放在场景中央,并将摄像机放在适当的位置来拍摄小球。 步骤二:设置摄像机位置和旋转 接下来,我们需要将摄像机的位置和旋转设置为固定的。具体步骤如下: 找到摄像机组件Ins…

    C# 2023年6月3日
    00
  • C# 泛型接口的抗变和协变

    C# 泛型接口的协变和抗变是面向对象编程中非常重要的概念,可以让我们更加方便和灵活地处理泛型类型的数据集合。在本篇攻略中,我们将会介绍C#泛型接口的抗变和协变的概念及其用法,并提供两个示例以帮助您理解。 什么是C#泛型接口? C# 泛型接口是一种在接口定义中使用类型参数的技术,它可以使接口更加通用,可以应用于多种数据类型。在C#中,我们通常使用泛型接口来定义…

    C# 2023年5月15日
    00
  • SQL语句执行超时引发网站首页访问故障问题

    问题分析 首先,我们需要检查网站首页访问故障的具体表现和报错信息。如果我们发现访问网站首页时,页面长时间无响应,或者出现“504 Gateway Timeout”之类的错误提示,那么很可能是由于SQL语句执行超时引发的故障。 其次,我们需要分析SQL语句执行超时的原因。这可能是因为SQL语句的复杂程度较高、数据库服务器负载过大,或者SQL语句本身存在性能问题…

    C# 2023年6月3日
    00
合作推广
合作推广
分享本页
返回顶部