ASP.NET Core MVC 打造一个简单的图书馆管理系统 (修正版)(七) 学生信息增删
前言:
本系列文章主要为我之前所学知识的一次微小的实践,以我学校图书馆管理系统为雏形所作。
本系列文章主要参考资料:
微软文档:https://docs.microsoft.com/zh-cn/aspnet/core/getting-started/?view=aspnetcore-2.1&tabs=windows
《Pro ASP.NET MVC 5》、《锋利的 jQuery》
此系列皆使用 VS2017+C# 作为开发环境。如果有什么问题或者意见欢迎在留言区进行留言。
项目 github 地址:https://github.com/NanaseRuri/LibraryDemo
本章内容:Ajax 提交自定义对象、Ajax 提交数组
此处全部都在 /AdminAccount/Index 页面完成。
一、学生信息编辑首页
创建一个 Admin 控制器用于编辑学生信息:
[Authorize(Roles = "Admin")]
public class AdminAccountController : Controller
{
private UserManager<Student> _userManager; public AdminAccountController(UserManager<Student> userManager)
{
_userManager = userManager;
} public IActionResult Index()
{
ICollection<Student> students = _userManager.Users.ToList();
return View(students);
}
}
视图:
@using LibraryDemo.Models.DomainModels
@model IEnumerable<LibraryDemo.Models.DomainModels.Student>
@{
ViewData["Title"] = "AccountInfo";
Student stu = new Student();
}
<link rel="stylesheet" href="~/css/BookInfo.css" /> <h2>学生信息</h2> <div id="buttonGroup">
<button class="btn btn-primary" onclick="return addStudent()">添加学生</button>
<button class="btn btn-danger" onclick="return confirmDelete()">删除学生</button>
</div> <br />
<table>
<thead>
<tr>
<th></th>
<th>@Html.LabelFor(m => stu.UserName)</th>
<th>@Html.LabelFor(m => stu.Name)</th>
<th>@Html.LabelFor(m => stu.Degree)</th>
<th>@Html.LabelFor(m => stu.PhoneNumber)</th>
<th>@Html.LabelFor(m => stu.Email)</th>
<th>@Html.LabelFor(m => stu.MaxBooksNumber)</th>
</tr>
</thead>
<tbody id="studentList"> @if (!@Model.Any())
{
<tr><td colspan="">未有学生信息</td></tr>
}
else
{
foreach (var student in Model)
{
<tr>
<td><input type="checkbox" name="userNames" value="@student.UserName" /></td>
<td>@student.UserName</td>
<td>@student.Name</td>
<td>@Html.DisplayFor(m => student.Degree)</td>
<td>@student.PhoneNumber</td>
<td>@student.Email</td>
<td>@student.MaxBooksNumber</td>
</tr>
}
}
</tbody>
</table>
结果:
二、增加新学生
此处打算使用 Ajax 来实现无刷新页面更新,因此动作方法返回类型为 Json 。
动作方法:
此处需注意在参数处添加 [FromBody] 修饰,否则无法读取来自页面的数据。
为节省带宽,此处仅返回添加的学生的 JSON 。
[HttpPost]
public async Task<JsonResult> AddStudent([FromBody]Student student)
{
if (_userManager.CreateAsync(student,"").Result.Succeeded)
{
return await AddedStudent(student.UserName);
} return Json("Failed");
} public async Task<JsonResult> AddedStudent(string userName)
{
Student student=await _userManager.Users.FirstOrDefaultAsync(s => s.UserName == userName);
return Json(new
{
userName = student.UserName,
name = student.Name,
degree = student.Degree == Degrees.CollegeStudent ? "本科生" : (student.Degree == Degrees.Postgraduate ? "研究生" : "博士生"),
phoneNumber = student.PhoneNumber,
email = student.Email,
maxBooksNumber = student.MaxBooksNumber
});
}
在视图中添加 JS 代码:
此处 JS 代码先是点击 添加书籍 按钮插入一行用于编辑的区域,然后通过插入区域的提交按钮提交信息,在信息成功返回后删除原来进行编辑的行,通过返回的信息添加新的行。
27-33 中由于 ASP.NET Core 后台返回 JSON 数据时会对数据的键的首字母进行小写处理,因此此处读取属性也是使用首字母小写,在后台的键也是使用首字母小写加以强调。
<script>
function postAddStudent() {
$.ajax({
url: "@Url.Action("AddStudent")",
contentType: "application/json",
method: "POST",
data: JSON.stringify({
UserName: $("#UserName").val(),
Name: $("#Name").val(),
Degree:$("#Degree").val(),
PhoneNumber: $("#PhoneNumber").val(),
Email: $("#Email").val(),
MaxBooksNumber: $("#MaxBooksNumber").val()
}),
success: function (student) {
addStudentToTable(student);
}
});
} function addStudentToTable(student) {
var studentList = document.getElementById("studentList");
var studentInfo = document.getElementById("studentInfo");
studentList.removeChild(studentInfo); $("#studentList").append(`<tr>` +
`<td><input type="checkbox" name="userNames" value="${student.userName}" /></td>` +
`<td>${student.userName}</td>` +
`<td>${student.name}</td>`+
`<td>${student.degree}</td>` +
`<td>${student.phoneNumber}</td>` +
`<td>${student.email}</td>` +
`<td>${student.maxBooksNumber}</td >` +
`</tr>`);
}
</script>
结果:
三、 批量移除学生
此处亦可以只返回更新过的元素,但为了演示 ASP.NET Core 使用 Ajax 对数组进行处理,故返回新的 Student 列表:
[HttpPost]
public async Task<JsonResult> RemoveStudent([FromBody]IEnumerable<string> userNames)
{
Student removedStudent;
foreach (var userName in userNames)
{
removedStudent =await _userManager.FindByNameAsync(userName);
if (removedStudent!=null)
{
await _userManager.DeleteAsync(removedStudent);
}
}
return GetStudentData();
} public JsonResult GetStudentData()
{
var students = _userManager.Users.Select(s =>new
{
userName=s.UserName,
name=s.Name,
degree=s.Degree==Degrees.CollegeStudent?"本科生":(s.Degree==Degrees.Postgraduate?"研究生":"博士生"),
phoneNumber = s.PhoneNumber,
email = s.Email,
maxBooksNumber = s.MaxBooksNumber
});
return Json(students);
}
视图添加 JS 函数:
18 行为数组元素的提交方式,不需像之前一样—— {values:values},否则无法进行数据绑定而导致后台接收到空数据。
为了对表格进行更新,先是通过 jQuery 获取了 tbody 的部分,清空后添加来自后台的新信息:
<script>
function confirmDelete() {
var userNames = document.getElementsByName("userNames");
var message = "确认删除";
var values = [];
for (i in userNames) {
if (userNames[i].checked) {
message = message + userNames[i].value+",";
values.push(userNames[i].value);
}
}
message = message + "?";
if (confirm(message)) {
$.ajax({
url: "@Url.Action("RemoveStudent")",
contentType: "application/json",
method: "POST",
data: JSON.stringify(values),
success: function(students) {
updateTable(students);
}
});
}
} function updateTable(data) {
var body = $("#studentList");
body.empty();
for (var i = ; i < data.length; i++) {
var person = data[i];
body.append(`<tr><td><input type="checkbox" name="userNames" value="${person.userName}" /></td>
<td>${person.userName}</td><td>${person.name}</td><td>${person.degree}</td>
<td>${person.phoneNumber}</td><td>${person.email}</td><td>${person.maxBooksNumber}</td></tr>`);
}
};
</script>
结果:
ASP.NET Core MVC 打造一个简单的图书馆管理系统 (修正版)(七) 学生信息增删的更多相关文章
- ASP.NET Core MVC 打造一个简单的图书馆管理系统 (修正版)(二)数据库初始化、基本登录页面以及授权逻辑的建立
前言: 本系列文章主要为我之前所学知识的一次微小的实践,以我学校图书馆管理系统为雏形所作. 本系列文章主要参考资料: 微软文档:https://docs.microsoft.com/zh-cn/asp ...
- ASP.NET Core MVC 打造一个简单的图书馆管理系统 (修正版)(六)学生借阅/预约/查询书籍事务
前言: 本系列文章主要为我之前所学知识的一次微小的实践,以我学校图书馆管理系统为雏形所作. 本系列文章主要参考资料: 微软文档:https://docs.microsoft.com/zh-cn/asp ...
- ASP.NET Core MVC 打造一个简单的图书馆管理系统 (修正版)(五)外借/阅览图书信息的增删改查
前言: 本系列文章主要为我之前所学知识的一次微小的实践,以我学校图书馆管理系统为雏形所作. 本系列文章主要参考资料: 微软文档:https://docs.microsoft.com/zh-cn/asp ...
- ASP.NET Core MVC 打造一个简单的图书馆管理系统 (修正版)(四)图书信息的增删改查
前言: 本系列文章主要为我之前所学知识的一次微小的实践,以我学校图书馆管理系统为雏形所作. 本系列文章主要参考资料: 微软文档:https://docs.microsoft.com/zh-cn/asp ...
- ASP.NET Core MVC 打造一个简单的图书馆管理系统 (修正版)(三)密码修改以及密码重置
前言: 本系列文章主要为我之前所学知识的一次微小的实践,以我学校图书馆管理系统为雏形所作. 本系列文章主要参考资料: 微软文档:https://docs.microsoft.com/zh-cn/as ...
- ASP.NET Core MVC 打造一个简单的图书馆管理系统 (修正版)(一) 基本模型以及数据库的建立
前言: 本系列文章主要为我之前所学知识的一次微小的实践,以我学校图书馆管理系统为雏形所作. 本系列文章主要参考资料: 微软文档:https://docs.microsoft.com/zh-cn/asp ...
- 002.Create a web API with ASP.NET Core MVC and Visual Studio for Windows -- 【在windows上用vs与asp.net core mvc 创建一个 web api 程序】
Create a web API with ASP.NET Core MVC and Visual Studio for Windows 在windows上用vs与asp.net core mvc 创 ...
- 在ASP.NET Core MVC中构建简单 Web Api
Getting Started 在 ASP.NET Core MVC 框架中,ASP.NET 团队为我们提供了一整套的用于构建一个 Web 中的各种部分所需的套件,那么有些时候我们只需要做一个简单的 ...
- 使用 ASP.NET Core MVC 创建 Web API——响应数据的内容协商(七)
使用 ASP.NET Core MVC 创建 Web API 使用 ASP.NET Core MVC 创建 Web API(一) 使用 ASP.NET Core MVC 创建 Web API(二) 使 ...
随机推荐
- 具体解释window.history
Window.history保存用户在一个会话期间的站点訪问记录,用户每次訪问一个新的URL即创建一个新的历史记录. history.go().history.back().history.forwa ...
- POJ 1083 && HDU 1050 Moving Tables (贪心)
Moving Tables Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) To ...
- linux系统之shell编程-正則表達式
shell编程正則表達式: 1:元字符 [ ] . * ? + ( ) | { } ^ $ 2 : [a-z0-9] 表示匹配随意数字和字母的一个 3 : [^a-z] ...
- TCP socket心跳包示例程序
在做游戏开发时,经常需要在应用层实现自己的心跳机制,即定时发送一个自定义的结构体(心跳包),让对方知道自己还活着,以确保连接的有效性. 在TCP socket心跳机制中,心跳包可以由服务器发送给客户端 ...
- 我所见过的最简短、最灵活的javascript日期转字符串工具函数
我们知道javascript的Date对象并没有提供日期格式化函数.将日期对象转换成"2015-7-02 20:35:11"等这样的格式又是项目中非经常常使用的需求.近期在我们项目 ...
- 第8章4节《MonkeyRunner源代码剖析》MonkeyRunner启动执行过程-启动AndroidDebugBridge
上一节我们看到在启动AndroidDebugBridge的过程中会调用其start方法,而该方法会做2个基本的事情: 715行startAdb:开启AndroidDebugBridge 722-723 ...
- Redis相关知识
Redis 存储的五种 字符串类型:string 一个String类型的value最大可以存储512M String是最常用的一种数据类型,普通的key/value存储. 散列类型: hash 键值 ...
- 对JS闭包的理解
闭包,是JS里很重要的一个概念,也是相对来讲不太容易理解的一个东西,不过即使难理解,我们也要迎难而上啊,嘿嘿,网上有很多文章都在讲闭包,我在看JS设计模式的时候,书里也着重讲了闭包,但是书里官方的的确 ...
- object equal
package equals; public class EqualsTest { public static void main(String[] args) { Employee alice1 = ...
- MIPS 指令集将在近期开源,RISC-V 阵营慌吗?
消息称,MIPS 指令集即将开源. eetimes 17 日报导,Wave Computing 公司表示,在明年第一季度发布最新 MIPS 指令集体系和 MIPS 最新内核 R6 的时候将开源 MIP ...