ASP.NET Core Identity + Mysql(实战三)——用户管理

简单效果展示
在这里插入图片描述
1.在Controllers中添加StudentControllers

using LibrarySystem.Web.Models;
using LibrarySystem.Web.ViewModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Threading.Tasks;

namespace LibrarySystem.Web.Controllers
{
    [Authorize]
    public class StudentController : Controller
    {
        private readonly UserManager<Student> _userManager;

        public StudentController(UserManager<Student> userManager)
        {
            _userManager = userManager;
        }

        public async Task<IActionResult> Index()
        {
            var users = await _userManager.Users.ToListAsync();

            return View(users);
        }

        public IActionResult Create()
        {
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> Create(StudentCreateViewModel studentCreateViewModel)
        {
            if (!ModelState.IsValid)
            {
                return View(studentCreateViewModel);
            }

            var user = new Student
            {
                UserName = studentCreateViewModel.UserName,
                Email = studentCreateViewModel.Email,
                SName = studentCreateViewModel.SName,
                PhoneNumber = studentCreateViewModel.PhoneNumber,
                SBirthDate = studentCreateViewModel.SBirthDate,
                SGender = studentCreateViewModel.SGender,
                SDegrees = studentCreateViewModel.SDegrees
            };

            var result = await _userManager.CreateAsync(user, studentCreateViewModel.Password);

            if (result.Succeeded)
            {
                return RedirectToAction("Index");
            }

            foreach (IdentityError error in result.Errors)
            {
                ModelState.AddModelError(string.Empty, error.Description);
            }

            return View(studentCreateViewModel);

        }

        public async Task<IActionResult> Edit(string id)
        {
            var user = await _userManager.FindByIdAsync(id);
            if (user == null)
            {
                return RedirectToAction("Index");
            }

            return View(user);
        }

        [HttpPost]
        public async Task<IActionResult> Edit(string id, StudentUpdateViewModel studentUpdateViewModel)
        {
            var user = await _userManager.FindByIdAsync(id);
            if (user == null)
            {
                return RedirectToAction("Index");
            }

            user.UserName = studentUpdateViewModel.UserName;
            user.Email = studentUpdateViewModel.Email;
            user.PhoneNumber = studentUpdateViewModel.PhoneNumber;
            user.SBirthDate = studentUpdateViewModel.SBirthDate;
            user.SName = studentUpdateViewModel.SName;
            user.SGender = studentUpdateViewModel.SGender;
            user.SDegrees = studentUpdateViewModel.SDegrees;

            var result = await _userManager.UpdateAsync(user);

            if (result.Succeeded)
            {
                return RedirectToAction("Index");
            }
            ModelState.AddModelError(string.Empty, "更新用户信息时发生错误");
            return View(user);
        }

        [HttpPost]
        public async Task<IActionResult> Delete(string id)
        {
            var user = await _userManager.FindByIdAsync(id);
            if (user != null)
            {
                var result = await _userManager.DeleteAsync(user);
                if (result.Succeeded)
                {
                    return RedirectToAction("Index");
                }

                ModelState.AddModelError(string.Empty, "删除用户时发生错误");
            }
            else
            {
                ModelState.AddModelError(string.Empty, "用户找不到");
            }

            return View("Index", await _userManager.Users.ToListAsync());
        }
    }
}

2.在ViewModels依次添加StudentCreateViewModel.cs、StudentUpdateViewModel.cs、StudentViewModel.cs

using LibrarySystem.Web.Models;
using System.ComponentModel.DataAnnotations;
using System;

namespace LibrarySystem.Web.ViewModels
{
    public class StudentCreateViewModel
    {
        [Display(Name = "学号")]
        public string UserName { get; set; }
        [Display(Name = "姓名")]
        public string SName { get; set; }
        [Display(Name = "手机号")]
        [StringLength(14, MinimumLength = 11)]
        public string PhoneNumber { get; set; }
        [Display(Name = "邮箱")]
        public string Email { get; set; }
        [Display(Name = "出生日期")]
        public DateTime SBirthDate { get; set; }
        [Display(Name = "性别")]
        public Gender SGender { get; set; }
        [Display(Name = "学位")]
        public Degrees SDegrees { get; set; }
        [Display(Name = "密码")]
        public string Password { get; set; }
    }
}
using LibrarySystem.Web.Models;
using System;
using System.ComponentModel.DataAnnotations;

namespace LibrarySystem.Web.ViewModels
{
    public class StudentUpdateViewModel
    {
        [Display(Name = "学号")]
        public string UserName { get; set; }
        [Display(Name = "姓名")]
        public string SName { get; set; }
        [Display(Name = "手机号")]
        public string PhoneNumber { get; set; }
        [Display(Name = "邮箱")]
        public string Email { get; set; }
        [Display(Name = "出生日期")]
        public DateTime SBirthDate { get; set; }
        [Display(Name = "性别")]
        public Gender SGender { get; set; }
        [Display(Name = "学位")]
        public Degrees SDegrees { get; set; }
    }
}
using System;

namespace LibrarySystem.Web.ViewModels
{
    public class StudentViewModel
    {
        public string UserName { get; set; }
        public string SName { get; set; }
        public string PhoneNumber { get; set; }
        public string Email { get; set; }
        public string SGender { get; set; }
        public DateTime SBirthDate { get; set; }
        public string SDegrees { get; set; }
    }
}

3.在View中添加Student文件夹,在文件夹中添加相应的视图
(1)Index.cshtml

@model IEnumerable<Student>

@{
    ViewBag.Title = "用户列表";
}

<h2>@ViewBag.Title</h2>

<table class="table">
    <thead class="thead-dark">
        <tr>
            <th scope="col">学号</th>
            <th scope="col">姓名</th>
            <th scope="col">Email</th>
            <th scope="col">手机号</th>
            <th scope="col">出生日期</th>
            <th scope="col">学位</th>
            <th scope="col">性别</th>
            <th scope="col">操作</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var u in Model)
        {
        <tr>
            <th scope="row"><a asp-action="Edit" asp-route-id="@u.Id">@u.UserName</a></th>
            <td>@u.SName</td>
            <td>@u.Email</td>
            <td>@u.PhoneNumber</td>
            <td>@u.SBirthDate</td>
            <td>@u.SDegrees</td>
            <td>@u.SGender</td>
            <td>
                <form asp-action="Delete" asp-route-id="@u.Id" method="post">
                    <a asp-action="Edit" asp-route-id="@u.Id" class="btn btn-primary">编辑</a>
                    <button type="submit" class="btn btn-danger"
                            onclick="return confirm('确认删除?')">
                        删除
                    </button>
                </form>
            </td>
        </tr>
        }
    </tbody>
</table>

<a asp-action="Create" class="btn btn-primary">添加用户</a>

(2)Create.cshtml

@model StudentCreateViewModel

<h1>创建学生</h1>

<form method="post">
    @*input不写类型时,默认是字符串类型*@
    <div>
        <label asp-for="UserName"></label>
        <input asp-for="UserName" />
        <span asp-validation-for="UserName"></span>
    </div>
    <div>
        <label asp-for="SName"></label>
        <input asp-for="SName" />
        <span asp-validation-for="SName"></span>
    </div>
    <div>
        <label asp-for="PhoneNumber"></label>
        <input asp-for="PhoneNumber" />
        <span asp-validation-for="PhoneNumber"></span>
    </div>
    <div>
        <label asp-for="Email"></label>
        <input asp-for="Email" />
        <span asp-validation-for="Email"></span>
    </div>
    <div>
        <label asp-for="SGender"></label>
        <select asp-for="SGender" asp-items="Html.GetEnumSelectList<Gender>()"></select>
        <span asp-validation-for="SGender"></span>
    </div>
    <div>
        <label asp-for="SBirthDate"></label>
        <input asp-for="SBirthDate" type="date" />
        <span asp-validation-for="SBirthDate"></span>
    </div>
    <div>
        <label asp-for="SDegrees"></label>
        <select asp-for="SDegrees" asp-items="Html.GetEnumSelectList<Degrees>()"></select>
        <span asp-validation-for="SDegrees"></span>
    </div>
    <div>
        <label asp-for="Password"></label>
        <input asp-for="Password" />
        <span asp-validation-for="Password"></span>
    </div>
    <div asp-validation-summary="ModelOnly"></div>

    <button type="submit" name="save">保存</button>
</form>

(3)Edit.cshtml

@model Student
@{
    ViewBag.Title = "编辑学生信息";
}

<form method="post">
    <div>
        <label asp-for="UserName"></label>
        <input asp-for="UserName" />
        <span asp-validation-for="UserName"></span>
    </div>
    <div>
        <label asp-for="SName"></label>
        <input asp-for="SName" />
        <span asp-validation-for="SName"></span>
    </div>
    <div>
        <label asp-for="PhoneNumber"></label>
        <input asp-for="PhoneNumber" />
        <span asp-validation-for="PhoneNumber"></span>
    </div>
    <div>
        <label asp-for="Email"></label>
        <input asp-for="Email" />
        <span asp-validation-for="Email"></span>
    </div>
    <div>
        <label asp-for="SGender"></label>
        <select asp-for="SGender" asp-items="Html.GetEnumSelectList<Gender>()"></select>
        <span asp-validation-for="SGender"></span>
    </div>
    <div>
        <label asp-for="SBirthDate"></label>
        <input asp-for="SBirthDate" type="date" />
        <span asp-validation-for="SBirthDate"></span>
    </div>
    <div>
        <label asp-for="SDegrees"></label>
        <select asp-for="SDegrees" asp-items="Html.GetEnumSelectList<Degrees>()"></select>
        <span asp-validation-for="SDegrees"></span>
    </div>
    <div asp-validation-summary="ModelOnly"></div>

    <button type="submit" class="btn btn-primary">提交</button>
    <a asp-action="Index" class="btn btn-secondary">返回列表</a>
</form>

(4)Delete.cshtml

@model Student
@{
    ViewBag.Title = "删除明细";
}

<h2>确认要删除该学生信息?</h2>
<h2>@Model.UserName  @Model.SName</h2>
<form method="post">
    <div class="form-group row">
        <div class="col-sm-12">
            <button type="submit" class="btn btn-danger">删除</button>
            <a asp-action="Index" class="btn btn-secondary">返回列表</a>
        </div>
    </div>
</form>

4.保存并运行
Index
Create

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我理解了你的问题。关于 Hangfire、MySQLASP.NET Core 3.1 的使用,我可以给出一些异常解决的建议。 首先,确保你已经按照官方文档正确地安装和配置了 Hangfire 和 MySQL。然后,根据你遇到的异常,尝试以下解决方法: 1. "Could not load file or assembly 'MySql.Data' or one of its dependencies" 异常 这个异常通常是由于缺少 MySQL 数据库驱动程序引起的。你需要在项目中添加对 MySQL 数据库驱动程序的引用。可以通过 NuGet 包管理器来安装 MySQL.Data。 2. "Specified key was too long; max key length is 767 bytes" 异常 这个异常是由于 MySQL 的索引长度限制引起的。解决方法是,在你的 DbContext 类中覆盖 OnModelCreating 方法,将所有字符串属性的最大长度设置为 255。 ``` protected override void OnModelCreating(ModelBuilder modelBuilder) { foreach (var property in modelBuilder.Model.GetEntityTypes() .SelectMany(t => t.GetProperties()) .Where(p => p.ClrType == typeof(string))) { property.SetMaxLength(255); } } ``` 3. "MySqlException: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding" 异常 这个异常通常是由于 MySQL 连接超时引起的。解决方法是,在连接字符串中添加 Connection Timeout 参数,例如: ``` "Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;Connection Timeout=60;" ``` 这将使连接超时时间为 60 秒。 希望这些解决方法能帮助你解决异常问题。如果你还有其他问题,请随时问我。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值