说明:本demo使用sqlserver数据库,dapper orm框架 完成一张学生信息表的增删改查,前端部分使用的是Razor视图,
Linq分页 HtmlHelper。(代码随便写的,具体可以自己优化)
//实现效果如下(首页)
//新增页
//修改页
//删除
1.使用visual stuido 2022创建 asp.net core mvc项目(选择如下图)
2.安装dapper nuget包(选择第一个)
3.使用sqlserver创建数据库和数据表
USE [stu]
GO
/****** Object: Table [dbo].[StuInfo] Script Date: 2023/9/28 18:17:23 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[StuInfo](
[Id] [int] NULL,
[Name] [nchar](10) NULL,
[Sex] [nchar](10) NULL,
[Age] [int] NULL,
[BirthDate] [date] NULL
) ON [PRIMARY]
GO
4.在项目appsetting中配置数据库连接字符串(填写自己的用户名和密码,和数据库信息)
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"connectionString": "Data Source=.;Initial Catalog=stu;User ID=sa;Password=pe123;TrustServerCertificate=true"
}
}
5.创建数据学生信息实体类
namespace mvccore.dataModel
{
public class StuInfo
{
public int Id { get; set; }
public string? Name { get; set; }
public string? Sex { get; set; }
public int Age { get; set; }
public DateTime BirthDate { get; set; }
}
}
6.创建学生信息dto类
namespace mvccore.ViewModel
{
public class stuViewModel
{
public int Id { get; set; }
public string? Name { get; set; }
public string? Sex { get; set; }
public int Age { get; set; }
}
}
7.创建stu的接口和实现类service(使用ioc注入面向接口编程)
创建接口和实现类后需要在program中注入服务
using mvccore.dataModel;
using mvccore.ViewModel;
namespace mvccore.service
{
public interface Istuservice
{
//查询
List<stuViewModel> stuls();
void save<T>(T stu);
void edit<T>(T t);
//删除
void delete(int Id);
//根据Id查询
stuViewModel GetById(int Id);
}
}
using mvccore.ViewModel;
using Dapper;
using Microsoft.Data.SqlClient;
using System.Collections.Generic;
using System.Collections;
using mvccore.dataModel;
namespace mvccore.service
{
public class stuservice : Istuservice
{
private readonly IConfiguration _configuration;
public string connstring { get; set; }
public stuservice(IConfiguration configuration)
{
_configuration = configuration;
connstring = _configuration.GetConnectionString("connectionString");
}
//删除
public void delete(int Id)
{
using (var connection = new SqlConnection(connstring))
{
string sql = "delete from StuInfo where Id=@Id";
connection.Execute(sql, new { Id });
}
}
//显示所有列表
public List<stuViewModel> stuls()
{
using (var connection = new SqlConnection(connstring))
{
string sql = "select * from StuInfo";
var list = connection.Query<stuViewModel>(sql).ToList();
return list;
}
}
//新增
public void save<T>(T stu1)
{
var stu = stu1 as stuViewModel;
using (var connection = new SqlConnection(connstring))
{
string sql = "insert into StuInfo(Id,Name,Sex,Age) values(@Id,@Name,@Sex,@Age);";
DynamicParameters parameters = new DynamicParameters();
parameters.Add("Id", 20);
parameters.Add("Name", stu.Name);
parameters.Add("Sex", stu.Sex);
parameters.Add("Age", stu.Age);
connection.Execute(sql, parameters);
}
}
//编辑
public void edit<T>(T t)
{
var stu = t as stuViewModel;
string sql = "update StuInfo set Name=@Name,Age=@Age WHERE Id=@Id";
using (var connection = new SqlConnection(connstring))
{
connection.Execute(sql, new { Name = stu?.Name, Age = stu?.Age, Id = stu?.Id });
}
}
//根据Id查询
public stuViewModel GetById(int Id)
{
string sql = "select * from StuInfo where Id=@Id";
using (var connection = new SqlConnection(connstring))
{
var list = connection.Query<stuViewModel>(sql, new { Id = Id }).FirstOrDefault();
return list;
}
}
}
}
8.创建分页类
namespace WebApplication4
{
public class PaginatedList<T> : List<T>
{
public int PageIndex { get; private set; }
public int TotalPages { get; private set; }
public PaginatedList(List<T> items, int count, int pageIndex, int pageSize)
{
PageIndex = pageIndex;
TotalPages = (int)Math.Ceiling(count / (double)pageSize);
this.AddRange(items);
}
public bool HasPreviousPage => PageIndex > 1;
public bool HasNextPage => PageIndex < TotalPages;
public static PaginatedList<T> Create(IQueryable<T> source, int pageIndex, int pageSize)
{
var count = source.Count();
var items = source.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
return new PaginatedList<T>(items, count, pageIndex, pageSize);
}
}
}
-------------------------------至此所有的业务代码就准备好了,接下来下控制器和视图里面的代码--------------------------------------------
9.创建stu的控制器
RedirectToAction(“StuInfoList”):是指定跳转到当前控制器下的其他视图,这里我们跳转到首页
using Microsoft.AspNetCore.Mvc;
using mvccore.service;
using mvccore.ViewModel;
using WebApplication4;
namespace mvccore.Controllers
{
public class StuController : Controller
{
private readonly Istuservice _stuservice;
public StuController(Istuservice stuservice)
{
_stuservice = stuservice;
}
//学生列表视图
public IActionResult StuInfoList(int? pageNumber = 1)
{
var list = _stuservice.stuls().ToList();
int pageSize = 3;
return View(PaginatedList<stuViewModel>.Create(list.AsQueryable(), pageNumber ?? 1, pageSize));
}
//保存视图
public IActionResult Save()
{
return View();
}
//保存方法
public IActionResult Save2(stuViewModel stu)
{
_stuservice.save<stuViewModel>(stu);
return RedirectToAction("StuInfoList");
}
//删除方法(正式项目我们一般使用逻辑删除,不会真的把数据删掉)
public IActionResult delete(int Id)
{
_stuservice?.delete(Id);
return RedirectToAction("StuInfoList");
}
//编辑回显
public IActionResult edit(int Id)
{
return View(_stuservice.GetById(Id));
}
//编辑方法
public IActionResult edit2(stuViewModel stu)
{
_stuservice?.edit(stu);
return RedirectToAction("StuInfoList");
}
}
}
10.添加首页的视图(StuInfoList.cshtml)
@model PaginatedList<mvccore.ViewModel.stuViewModel>
@Html.ActionLink("新增","Save","Stu")
<table class="table">
<tr>
<th>Name</th>
<th>Age</th>
<th>Sex</th>
<td>操作</td>
</tr>
@foreach (var item in Model)
{
<tr>
<td>@item.Name</td>
<td>@item.Age</td>
<td>@item.Sex</td>
<td> @Html.ActionLink("编辑","edit","Stu",new{item.Id}) @Html.ActionLink("删除","delete","Stu",new{@item.Id},new { onclick="return confirm('是否删除')" })</td>
</tr>
}
</table>
@{
var prevDisabled = !Model.HasPreviousPage ? "disabled" : "";
var nextDisabled = !Model.HasNextPage ? "disabled" : "";
}
<a asp-action="StuInfoList"
asp-route-pageNumber="@(Model.PageIndex - 1)"
class="btn btn-default @prevDisabled">
Previous
</a>
<a asp-action="StuInfoList"
asp-route-pageNumber="@(Model.PageIndex + 1)"
class="btn btn-default @nextDisabled">
Next
</a>
11.添加新增视图(Save.cshtml)
<form action="/stu/Save2" method="post">
姓名:<input type="text" name="Name" />
年龄:<input type="text" name="Age"/>
性别:<input type="text" name="Sex"/>
<input type="submit" value="保存"/>
</form>
12.添加编辑视图(edit.cshtml)(可以和新增公用一个视图)
@using mvccore.ViewModel
@model stuViewModel;
<form action="/stu/edit2" method="post">
姓名:<input type="text" name="Name" value="@Model.Name" />
年龄:<input type="text" name="Age" value="@Model.Age" />
<input type="hidden" name="Id" value="@Model.Id"/>
<input type="submit" value="保存" />
</form>
13.如果在解决方案中有多个项目的话,需要把当前项目设置为启动项目
14.修改项目默认起始页,默认路由是 /Home/index(根据自己的需要更改)
15.End 至此项目demo就完成了,下面是项目的结构图
代码随便写的,主要是快速入门。这边可以去微软官方文档上学习,有完整的代码实例(网址如下)
https://learn.microsoft.com/zh-cn/aspnet/core/tutorials/first-mvc-app/start-mvc?view=aspnetcore-7.0&tabs=visual-studio