• asp.net core mvc Razor +dapper 增删改查,分页(保姆教程)


    说明:本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
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    4.在项目appsetting中配置数据库连接字符串(填写自己的用户名和密码,和数据库信息)

    {
      "Logging": {
        "LogLevel": {
          "Default": "Information",
          "Microsoft.AspNetCore": "Warning"
        }
      },
      "AllowedHosts": "*",
      "ConnectionStrings": {
        "connectionString": "Data Source=.;Initial Catalog=stu;User ID=sa;Password=pe123;TrustServerCertificate=true"
      }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    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; }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    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; }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    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);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    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;
                }
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80

    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);
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

    -------------------------------至此所有的业务代码就准备好了,接下来下控制器和视图里面的代码--------------------------------------------
    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");
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53

    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>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40

    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>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    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>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    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

  • 相关阅读:
    Spring Boot 3.2四个新特点提升运行性能
    直播岗位认知篇
    python模块之aioHttp 异步请求
    Checkerboard Artifacts(棋盘伪影)的发生以及解决方案:
    Google Earth Engine APP(GEE)—设定中国区域的一个夜间灯光时序分析app
    文举论金:黄金原油全面走势分析策略独家指导
    Win10 CMD命令大全 命令提示符常用命令有哪些
    腾讯T14开源的“Oracle与MySQL实战手册”看完被彻底惊艳了
    java毕业设计健身房信息管理mp4(附源码、数据库)
    Kafka进阶
  • 原文地址:https://blog.csdn.net/qq_41942413/article/details/133387965