首页 > 数据库 >七天.NET 8操作SQLite入门到实战 - 第七天Blazor学生管理页面编写和接口对接(3)

七天.NET 8操作SQLite入门到实战 - 第七天Blazor学生管理页面编写和接口对接(3)

时间:2024-07-28 14:06:32浏览次数:19  
标签:SQLite Task false await Blazor var using NET response

前言

本章节我们的主要内容是完善Blazor学生管理页面的编写和接口对接。

七天.NET 8 操作 SQLite 入门到实战详细教程

EasySQLite 项目源码地址

Blazor简介和快速入门

不熟悉Blazor的同学可以先看这篇文章大概了解一下。

全面的ASP.NET Core Blazor简介和快速入门

前端Table页面和接口对接代码

主要是常见Table的数据展示、数据添加、数据删除、数据修改等操作。

@page "/Student"
@using Entity
@using Entity.ViewModel
@using System.Reflection
@using Utility
@using WebUI.Common
@using WebUI.Services
@inject HttpClient _httpClient;
@inject DataLoaderService _dataLoader;

<Table TItem="StudentViewModel"
       AutoGenerateColumns="true"
       ShowToolbar="true"
       IsMultipleSelect="true"
       OnSaveAsync="@OnSaveAsync"
       OnQueryAsync="@OnQueryAsync"
       OnDeleteAsync="@OnDeleteAsync"
       IsStriped="true"
       IsBordered="true"
       ShowSearch="true"
       IsPagination="true"
       ShowSearchText="true">

    <!--通过设置 EditTemplate 自定义编辑弹窗,如果属性需要联动时必须像本例这样封装成一个独立的组件再放置到模板中-->
    <EditTemplate>
        <StudentEditor @bind-Value="context" />
    </EditTemplate>

    <SearchTemplate>
        <GroupBox Title="搜索条件">
            <div class="row g-3 form-inline">
                <div class="col-12 col-sm-6">
                    <BootstrapInput @bind-Value="@context.Name" PlaceHolder="请输入学生姓名" maxlength="50" ShowLabel="true" DisplayText="姓名" />
                </div>
            </div>
        </GroupBox>
    </SearchTemplate>
</Table>

@code {

    /// <summary>
    /// 数据查询
    /// </summary>
    /// <param name="options">options</param>
    /// <returns></returns>
    private async Task<QueryData<StudentViewModel>> OnQueryAsync(QueryPageOptions options)
    {
        var searchModel = options.SearchModel as StudentViewModel;
        var getStudentData = new List<StudentViewModel>();
        var getResults = await _httpClient.GetFromJsonAsync<ApiResponse<List<StudentViewModel>>>("api/Student/GetAllStudent").ConfigureAwait(false);
        if (getResults.Success)
        {
            // 数据模糊过滤筛选
            if (!string.IsNullOrWhiteSpace(options.SearchText))
            {
                getStudentData = getResults.Data.Where(x => x.Name.Contains(options.SearchText)).ToList();
            }
            else if (searchModel != null && !string.IsNullOrWhiteSpace(searchModel.Name))
            {
                getStudentData = getResults.Data.Where(x => x.Name.Contains(searchModel.Name)).ToList();
            }
            else
            {
                getStudentData = getResults.Data.ToList();
            }
        }

        //加载班级信息
        await _dataLoader.LoadSchoolClassDataAsync().ConfigureAwait(false);

        // 内存分页
        return await Task.FromResult(new QueryData<StudentViewModel>()
            {
                Items = getStudentData.Skip((options.PageIndex - 1) * options.PageItems).Take(options.PageItems).ToList(),
                TotalCount = getStudentData.Count()
            });
    }

    /// <summary>
    /// 模拟数据增加和修改操作
    /// </summary>
    /// <param name="studentInfo">studentInfo</param>
    /// <param name="changedType">changedType</param>
    /// <returns></returns>
    public async Task<bool> OnSaveAsync(StudentViewModel studentInfo, ItemChangedType changedType)
    {
        if (changedType.ToString() == "Update")
        {
            var addResult = await _httpClient.PutAsJsonAsync($"api/Student/UpdateStudent/{studentInfo.StudentID}", studentInfo).ConfigureAwait(false);
            if (UtilityBusiness.CheckResponse(addResult))
            {
                return await Task.FromResult(true);
            }
            else
            {
                return await Task.FromResult(false);
            }
        }
        else if (changedType.ToString() == "Add")
        {
            var addResult = await _httpClient.PostAsJsonAsync("api/Student/CreateStudent", studentInfo).ConfigureAwait(false);
            if (UtilityBusiness.CheckResponse(addResult))
            {
                return await Task.FromResult(true);
            }
            else
            {
                return await Task.FromResult(false);
            }
        }

        return await Task.FromResult(true);
    }

    /// <summary>
    /// 数据删除
    /// </summary>
    /// <param name="items">items</param>
    /// <returns></returns>
    private async Task<bool> OnDeleteAsync(IEnumerable<StudentViewModel> items)
    {
        var deleteSuccessNum = 0;
        var StudentViewModelList = items.ToList();
        foreach (var item in StudentViewModelList)
        {
            var delResult = await _httpClient.DeleteAsync($"api/Student/DeleteStudent/{item.StudentID}").ConfigureAwait(false);
            if (UtilityBusiness.CheckResponse(delResult))
            {
                deleteSuccessNum++;
            }
        }

        if (deleteSuccessNum > 0)
        {
            return await Task.FromResult(true);
        }
        else
        {
            return await Task.FromResult(false);
        }
    }
}

自定义编辑弹窗模板

StudentEditor.razor:

@using Entity
@using Microsoft.Extensions.Caching.Memory
@using WebUI.Services
@inject HttpClient _httpClient;
@inject DataLoaderService _dataLoader;
@inject IMemoryCache _memoryCache;

<div class="row g-3 form-inline">
    <div class="col-12">
        <BootstrapInput @bind-Value="@Value.ClassID" IsDisabled maxlength="50" />
    </div>
    <div class="col-12">
        <Select @bind-Value="@Value.ClassID" OnSelectedItemChanged="OnSelectedItemChanged" Items="Items" />
    </div>
    <div class="col-12">
        <BootstrapInput @bind-Value="@Value.Name" placeholder="请输入学生名称" maxlength="50" required />
    </div>
    <div class="col-12">
        <Select @bind-Value="@Value.Gender" Items="GenderItems" required />
    </div>
    <div class="col-12">
        <BootstrapInput @bind-Value="@Value.Age" placeholder="请输入年龄" maxlength="50" />
    </div>
</div>

StudentEditor.razor.cs:

using System;
using System.Diagnostics.CodeAnalysis;
using System.Net.Http;
using System.Net.Http.Json;
using System.Xml.Linq;
using BootstrapBlazor.Components;
using Entity;
using Entity.ViewModel;
using Microsoft.AspNetCore.Components;
using Microsoft.Extensions.Caching.Memory;
using Newtonsoft.Json;
using WebUI.Services;

namespace WebUI.Pages
{
    public partial class StudentEditor
    {
        [Parameter]
        public StudentViewModel Value { get; set; }

        [Parameter]
        public EventCallback<StudentViewModel> ValueChanged { get; set; }

        [NotNull]
        private List<SelectedItem>? Items { get; set; }

        [NotNull]
        private List<SelectedItem>? GenderItems { get; set; }

        protected override async void OnInitialized()
        {
            base.OnInitialized();
            List<SchoolClass>? getSchoolClass;
            if (_memoryCache.TryGetValue("SchoolClassData", out string data))
            {
                getSchoolClass = JsonConvert.DeserializeObject<List<SchoolClass>>(data);
            }
            else
            {
                getSchoolClass = await _dataLoader.LoadSchoolClassDataAsync().ConfigureAwait(false);
            }

            Items = [];
            foreach (var item in getSchoolClass.OrderBy(x => x.ClassID).ToList())
            {
                Items.Add(new SelectedItem { Value = item.ClassID.ToString(), Text = item.ClassName });
            }

            if (string.IsNullOrWhiteSpace(Value.ClassName))
            {
                Value.ClassName = Items.First().Text;
                Value.ClassID = Convert.ToInt32(Items.First().Value);
            }

            GenderItems = [new SelectedItem { Value = "男", Text = "男" }, new SelectedItem { Value = "女", Text = "女" }];

            if (string.IsNullOrWhiteSpace(Value.Gender))
            {
                Value.Gender = GenderItems.First().Text;
            }
        }

        /// <summary>
        /// 下拉框选项改变时触发此事件
        /// </summary>
        /// <param name="item">item</param>
        /// <returns></returns>
        async Task OnSelectedItemChanged(SelectedItem item)
        {
            await Task.Delay(1);
            Value.ClassID = Convert.ToInt32(item.Value);
        }
    }
}

后端API接口

using AutoMapper;
using Entity;
using Entity.ViewModel;
using Microsoft.AspNetCore.Mvc;
using Utility;

namespace WebApi.Controllers
{
    /// <summary>
    /// 学生管理
    /// </summary>
    [ApiController]
    [Route("api/[controller]/[action]")]
    public class StudentController : ControllerBase
    {
        private readonly IMapper _mapper;
        private readonly SQLiteAsyncHelper<Student> _studentHelper;
        private readonly SQLiteAsyncHelper<SchoolClass> _schoolClassHelper;

        /// <summary>
        /// 依赖注入
        /// </summary>
        /// <param name="mapper">mapper</param>
        /// <param name="studentHelper">studentHelper</param>
        /// <param name="schoolClassHelper">schoolClassHelper</param>
        public StudentController(IMapper mapper, SQLiteAsyncHelper<Student> studentHelper, SQLiteAsyncHelper<SchoolClass> schoolClassHelper)
        {
            _mapper = mapper;
            _studentHelper = studentHelper;
            _schoolClassHelper = schoolClassHelper;
        }

        /// <summary>
        /// 创建新的学生记录
        /// </summary>
        /// <param name="student">添加的学生信息</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResponse<int>> CreateStudent([FromBody] Student student)
        {
            var response = new ApiResponse<int>();
            try
            {
                var insertNumbers = await _studentHelper.InsertAsync(student).ConfigureAwait(false);
                if (insertNumbers > 0)
                {
                    response.Success = true;
                    response.Message = "添加成功";
                }
                else
                {
                    response.Success = false;
                    response.Message = "插入失败";
                }
            }
            catch (Exception ex)
            {
                response.Success = false;
                response.Message = ex.Message;
            }
            return response;
        }

        /// <summary>
        /// 查询所有学生记录
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResponse<List<StudentViewModel>>> GetAllStudent()
        {
            var response = new ApiResponse<List<StudentViewModel>>();
            try
            {
                var students = await _studentHelper.QueryAllAsync().ConfigureAwait(false);
                var studentsListDto = await GetStudentClassInfo(students).ConfigureAwait(false);
                response.Success = true;
                response.Data = studentsListDto ?? new List<StudentViewModel>();
            }
            catch (Exception ex)
            {
                response.Success = false;
                response.Message = ex.Message;
            }
            return response;
        }

        private async Task<List<StudentViewModel>?> GetStudentClassInfo(List<Student> students)
        {
            var studentsListDto = _mapper.Map<List<StudentViewModel>>(students);
            if (studentsListDto?.Count > 0)
            {
                var classIDs = studentsListDto.Select(x => x.ClassID).Distinct().ToList();
                var querySchoolClassList = await _schoolClassHelper.QueryAsync(x => classIDs.Contains(x.ClassID)).ConfigureAwait(false);
                if (querySchoolClassList?.Count > 0)
                {
                    foreach (var studentItem in studentsListDto)
                    {
                        var getClassInfo = querySchoolClassList.FirstOrDefault(x => x.ClassID == studentItem.ClassID);
                        if (getClassInfo != null)
                        {
                            studentItem.ClassName = getClassInfo.ClassName;
                        }
                    }
                }
            }
            return studentsListDto;
        }

        /// <summary>
        /// 根据学生ID查询学生信息
        /// </summary>
        /// <param name="studentID">学生ID</param>
        /// <returns></returns>
        [HttpGet("{studentID}")]
        public async Task<ApiResponse<StudentViewModel>> GetStudentById(int studentID)
        {
            var response = new ApiResponse<StudentViewModel>();
            try
            {
                var student = await _studentHelper
                    .QuerySingleAsync(x => x.StudentID == studentID)
                    .ConfigureAwait(false);
                if (student != null)
                {
                    var studentsDto = await GetStudentClassInfo(new List<Student> { student }).ConfigureAwait(false);
                    response.Success = true;
                    response.Data = studentsDto.FirstOrDefault();
                }
                else
                {
                    response.Success = false;
                    response.Message = "未找到学生信息";
                }
            }
            catch (Exception ex)
            {
                response.Success = false;
                response.Message = ex.Message;
            }
            return response;
        }

        /// <summary>
        /// 更新学生记录
        /// </summary>
        /// <param name="studentID">学生ID</param>
        /// <param name="editstudent">更新的学生信息</param>
        /// <returns></returns>
        [HttpPut("{studentID}")]
        public async Task<ApiResponse<int>> UpdateStudent(
            int studentID,
            [FromBody] Student editstudent
        )
        {
            var response = new ApiResponse<int>();
            try
            {
                var student = await _studentHelper
                    .QuerySingleAsync(x => x.StudentID == studentID)
                    .ConfigureAwait(false);
                if (student != null)
                {
                    student.Age = editstudent.Age;
                    student.Name = editstudent.Name;
                    student.Gender = editstudent.Gender;
                    student.ClassID = editstudent.ClassID;

                    int updateResult = await _studentHelper
                        .UpdateAsync(student)
                        .ConfigureAwait(false);
                    if (updateResult > 0)
                    {
                        response.Success = true;
                        response.Message = "学生信息更新成功";
                    }
                    else
                    {
                        response.Success = false;
                        response.Message = "学生信息更新失败";
                    }
                }
                else
                {
                    response.Success = false;
                    response.Message = "未找到学生信息";
                }
            }
            catch (Exception ex)
            {
                response.Success = false;
                response.Message = ex.Message;
            }
            return response;
        }

        /// <summary>
        /// 删除学生记录
        /// </summary>
        /// <param name="studentID">学生ID</param>
        /// <returns></returns>
        [HttpDelete("{studentID}")]
        public async Task<ApiResponse<int>> DeleteStudent(int studentID)
        {
            var response = new ApiResponse<int>();
            try
            {
                int deleteResult = await _studentHelper
                    .DeleteAsync(studentID)
                    .ConfigureAwait(false);
                if (deleteResult > 0)
                {
                    response.Success = true;
                    response.Message = "删除成功";
                }
                else
                {
                    response.Success = false;
                    response.Message = "未找到学生信息";
                }
            }
            catch (Exception ex)
            {
                response.Success = false;
                response.Message = ex.Message;
            }
            return response;
        }
    }
}

标签:SQLite,Task,false,await,Blazor,var,using,NET,response
From: https://www.cnblogs.com/Can-daydayup/p/18328182

相关文章

  • stable diffusion中的UNet2DConditionModel代码解读
    UNet2DConditionModel总体结构图片来自于https://zhuanlan.zhihu.com/p/635204519stablediffusion运行unet部分的代码。noise_pred=self.unet(sample=latent_model_input,#(2,4,64,64)生成的latenttimestep=t,#时刻tencoder_hidden_states=pro......
  • 如何强制某些节点在networkX中具有特定颜色
    我想要为networkx图的节点着色,但我也希望能够强制一组节点为特定颜色,同时仍然能够正确地为图中的所有节点着色。有谁知道如何做到这一点?可以通过将color属性传递给nx.draw函数,以将特定节点强制为特定颜色,同时仍然能够正确地为图形中的所有节点着色。......
  • C#(asp.net)二手手机交易平台设计与实现33627-计算机毕业设计项目选题推荐(附源码)
    摘 要信息化社会内需要与之针对性的信息获取途径,但是途径的扩展基本上为人们所努力的方向,由于站在的角度存在偏差,人们经常能够获得不同类型信息,这也是技术最为难以攻克的课题。针对二手手机交易平台等问题,对二手手机交易平台进行研究分析,然后开发设计出二手手机交易平台......
  • 使用 Python 进行 Web 抓取以获取数据 NoneType ERROR
    我正在努力为我的学校项目获取美元和价格。所以我决定为此使用网络抓取,但我有一个问题。当我尝试在服务器上使用我的代码时,它给我NoneType错误。它可以在googlecolab上使用,但我无法在我的电脑或服务器上使用。我该如何解决这个问题?网页抓取代码;defdolar():he......
  • 一款.NET开源、跨平台的DASH/HLS/MSS下载工具
    思维导航前言网络流媒体传输协议介绍工具源代码命令行参数工具运行截图项目源码地址优秀项目和框架精选前言今天大姚给大家分享一款.NET开源(MITLicense)、免费、跨平台的DASH/HLS/MSS下载工具,并且支持点播和直播(DASH/HLS)的内容下载:N_m3u8DL-RE。网络流媒体传输协......
  • 手把手教你集成GraphRag.Net:打造智能图谱搜索系统
        在人工智能和大数据发展的背景下,我们常常需要在项目中实现知识图谱的应用,以便快速、准确地检索和使用信息。        今天,我将向大家详细介绍如何在一个新的.NET项目中集成GraphRag.Net,这是一个参考GraphRag实现的.NET版本,能够实现图谱数据的存储、检索、和问......
  • 经典CNN模型(九):MobileNetV3(PyTorch详细注释版)
    一.MobileNetV3神经网络介绍MobileNetV3是MobileNet系列的第三代模型,由Google在2019年提出,旨在进一步优化模型的效率和性能,特别是在移动设备和边缘计算设备上。与前一代相比,MobileNetV3引入了多项改进,包括使用神经架构搜索(NeuralArchitectureSearch,NAS)、自适......
  • 一款.NET开源、跨平台的DASH/HLS/MSS下载工具
    前言今天大姚给大家分享一款.NET开源(MITLicense)、免费、跨平台的DASH/HLS/MSS下载工具,并且支持点播和直播(DASH/HLS)的内容下载:N_m3u8DL-RE。网络流媒体传输协议介绍DASHDASH是一种基于HTTP的自适应流媒体网络传输协议,它允许流媒体内容以多个编码和比特率的形式进行分发,客户端......
  • skynet热更新之inject
    游戏服务器的热更新是一种常见的需求,skynet可以通过inject的方式,来修改一个服务的消息处理函数,达到热更新的效果。skynet内置服务debug_consoleskynet自带了一个调试控制台服务。inject注入代码需要先启动这个服务。skynet.newservice("debug_console","127.0.0.1","9666")......
  • LSTNet RuntimeError:输入和参数张量不在同一设备上
    我克隆了一个githubrepo它运行一个pytorch深度学习模块,我定制了这部分以将模块和数据发送到GPU。train_dataset=MarketDataset(train_data,history_len=history_len)train_data_loader=DataLoader(train_dataset,batch_size=batch_size,shuffle=True)model......