asp.net core mvc Razor +dapper add, delete, modify, check, paging (nanny tutorial)

Note: This demo uses the sqlserver database and the dapper orm framework to complete the addition, deletion, modification and query of a student information table. The front-end part uses Razor view and
Linq paging HtmlHelper. (The code can be written casually, you can optimize it yourself)
//The implementation effect is as follows (home page)
Insert image description here
//New page
Insert image description here
//Modify page
Insert image description here
//Delete
Insert image description here
1. Use visual studio 2022 to create an asp.net core mvc project (select the picture below)
Insert image description here
2 .Install dapper nuget package (select the first one)
Insert image description here
3. Use sqlserver to create database and data table

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. Configure the database connection string in the project appsetting (fill in your user name and password, and database information)

{
    
    
  "Logging": {
    
    
    "LogLevel": {
    
    
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    
    
    "connectionString": "Data Source=.;Initial Catalog=stu;User ID=sa;Password=pe123;TrustServerCertificate=true"
  }
}

5. Create data student information entity class

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. Create student information dto class

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. Create the interface and implementation class service of stu (use ioc injection for interface-oriented programming).
After creating the interface and implementation class, you need to inject the service into the program.
Insert image description here

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.Create paging class

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);
        }
    }
}

----------------------------------Now all the business code is ready. Next, download the controller and view. Code----------------------------------------------
9. Create stu Controller
RedirectToAction("StuInfoList"): specifies to jump to other views under the current controller. Here we jump to the home page.

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. Add the view of the homepage (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. Add new view (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. Add editing view (edit.cshtml) (can share the same view with the new one)

@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. If there are multiple projects in the solution, you need to set the current project as the startup project
Insert image description here
14. Modify the project's default start page. The default route is /Home/index (change it according to your needs)

Insert image description here
15.End The project demo is now complete. The following is the structure diagram of the project.
Insert image description here
The code is written casually, mainly for quick start. You can go to Microsoft's official documentation to learn here. There are complete code examples (the URL is as follows)
https://learn.microsoft.com/zh-cn/aspnet/core/tutorials/first-mvc-app/start-mvc?view =aspnetcore-7.0&tabs=visual-studio

Guess you like

Origin blog.csdn.net/qq_41942413/article/details/133387965
Recommended