EducationStatus crud с выбором из списка «Студенты» записи к ней

This commit is contained in:
Danil Markov 2023-05-17 22:54:39 +04:00
parent 91212b9254
commit c87f2caaac
23 changed files with 692 additions and 30 deletions

View File

@ -71,6 +71,11 @@ namespace UniversityBusinessLogic.BusinessLogics
return list;
}
public int GetNumberOfPages(int userId, int pageSize = 10)
{
return _esStorage.GetNumberOfPages(userId, pageSize);
}
private void CheckModel(EducationStatusBindingModel model, bool withParams = true)
{
if (model == null)

View File

@ -16,5 +16,6 @@ namespace UniversityContracts.BusinessLogicContracts
bool Delete(EducationStatusBindingModel model);
List<EducationStatusViewModel>? ReadList(EducationStatusSearchModel? model);
EducationStatusViewModel? ReadElement(EducationStatusSearchModel model);
public int GetNumberOfPages(int userId, int pageSize = 10);
}
}

View File

@ -11,5 +11,7 @@ namespace UniversityContracts.SearchModels
public int? Id { get; set; }
public string? Name { get; set; }
public int? UserId { get; set; }
public int? PageNumber { get; set; }
public int? PageSize { get; set; }
}
}

View File

@ -11,10 +11,10 @@ namespace UniversityContracts.SearchModels
public int? Id { get; set; }
public int? StudentCard { get; set; }
public int? UserId { get; set; }
public int? EducationStatusId { get; set; }
public DateTime? DateFrom { get; set; }
public DateTime? DateTo { get; set; }
public bool? Disciplines { get; set; }
public int? PageNumber { get; set; }
public int? PageSize { get; set; }
}

View File

@ -17,5 +17,6 @@ namespace UniversityContracts.StoragesContracts
EducationStatusViewModel? Insert(EducationStatusBindingModel model);
EducationStatusViewModel? Update(EducationStatusBindingModel model);
EducationStatusViewModel? Delete(EducationStatusBindingModel model);
public int GetNumberOfPages(int userId, int pageSize = 10);
}
}

View File

@ -27,6 +27,7 @@ namespace UniversityDataBaseImplemet.Implements
|| record.Name.Equals(model.Name))
?.GetViewModel;
}
public List<EducationStatusViewModel> GetFilteredList(EducationStatusSearchModel model)
{
using var context = new Database();
@ -51,6 +52,7 @@ namespace UniversityDataBaseImplemet.Implements
return new();
}
}
public List<EducationStatusViewModel> GetFullList()
{
using var context = new Database();
@ -59,6 +61,7 @@ namespace UniversityDataBaseImplemet.Implements
.Select(record => record.GetViewModel)
.ToList();
}
public EducationStatusViewModel? Insert(EducationStatusBindingModel model)
{
var newEducationStatus = EducationStatus.Create(model);
@ -74,6 +77,7 @@ namespace UniversityDataBaseImplemet.Implements
.FirstOrDefault(record => record.Id.Equals(newEducationStatus.Id))
?.GetViewModel;
}
public EducationStatusViewModel? Update(EducationStatusBindingModel model)
{
using var context = new Database();
@ -98,6 +102,7 @@ namespace UniversityDataBaseImplemet.Implements
throw;
}
}
public EducationStatusViewModel? Delete(EducationStatusBindingModel model)
{
using var context = new Database();
@ -112,5 +117,13 @@ namespace UniversityDataBaseImplemet.Implements
context.SaveChanges();
return educationStatus.GetViewModel;
}
public int GetNumberOfPages(int userId, int pageSize)
{
using var context = new Database();
int carsCount = context.Students.Where(c => c.UserId == userId).Count();
int numberOfpages = (int)Math.Ceiling((double)carsCount / pageSize);
return numberOfpages != 0 ? numberOfpages : 1;
}
}
}

View File

@ -43,6 +43,8 @@ namespace UniversityDataBaseImplemet.Implements
if (model.UserId.HasValue && model.PageNumber.HasValue && model.PageSize.HasValue)
{
return context.Students
.Include(record => record.User)
.Include(record => record.EducationStatus)
.Where(x => x.UserId == model.UserId)
.Skip(model.PageSize.Value * (model.PageNumber.Value - 1))
.Take(model.PageSize.Value)
@ -58,6 +60,15 @@ namespace UniversityDataBaseImplemet.Implements
.Select(record => record.GetViewModel)
.ToList();
}
else if (model.UserId.HasValue && model.EducationStatusId.HasValue)
{
return context.Students
.Include(record => record.User)
.Include(record => record.EducationStatus)
.Where(record => record.UserId == model.UserId && record.EducationStatusId != model.EducationStatusId)
.Select(record => record.GetViewModel)
.ToList();
}
else if (model.UserId.HasValue)
{
return context.Students

View File

@ -0,0 +1,103 @@
using Microsoft.AspNetCore.Mvc;
using UniversityContracts.BindingModels;
using UniversityContracts.ViewModels;
namespace UniversityProvider.Controllers
{
public class EducationStatusController : Controller
{
public IActionResult Create()
{
if (APIClient.User == null)
{
return Redirect("~/Home/Enter");
}
return View();
}
[HttpPost]
public void Create([FromBody] EducationStatusBindingModel educationstatusModel)
{
if (APIClient.User == null)
{
throw new Exception("403");
}
educationstatusModel.UserId = APIClient.User.Id;
APIClient.PostRequest("api/educationstatus/create", educationstatusModel);
Response.Redirect("/Home/EducationStatuses");
}
public IActionResult Update(int id)
{
if (APIClient.User == null)
{
return Redirect("~/Home/Enter");
}
ViewBag.EducationStatus = APIClient.GetRequest<EducationStatusViewModel>($"api/educationstatus/get?id={id}");
return View();
}
[HttpPost]
public void Update([FromBody] EducationStatusBindingModel educationstatusModel)
{
if (APIClient.User == null)
{
throw new Exception("403");
}
educationstatusModel.UserId = APIClient.User.Id;
APIClient.PostRequest("api/educationstatus/update", educationstatusModel);
Response.Redirect("/Home/EducationStatuses");
}
public IActionResult AddStudent(int id)
{
if (APIClient.User == null)
{
return Redirect("~/Home/Enter");
}
ViewBag.EducationStatusId = id;
return View();
}
[HttpPost]
public void AddStudent([FromBody] StudentBindingModel studentModel)
{
if (APIClient.User == null)
{
throw new Exception("403");
}
APIClient.PostRequest("api/student/update", studentModel);
}
[HttpPost]
public void Delete(int id)
{
if (APIClient.User == null)
{
throw new Exception("403");
}
APIClient.PostRequest($"api/educationstatus/delete", new EducationStatusBindingModel() { Id = id });
Response.Redirect("/Home/EducationStatuses");
}
public List<EducationStatusViewModel> GetAllByUser()
{
if (APIClient.User == null)
{
return new();
}
List<EducationStatusViewModel>? educationstatus = APIClient.GetRequest<List<EducationStatusViewModel>>($"api/educationstatus/getallbyuser?userId={APIClient.User.Id}");
return educationstatus ?? new();
}
public EducationStatusViewModel? Get(int id)
{
if (APIClient.User == null)
{
return new();
}
EducationStatusViewModel? educationstatus = APIClient.GetRequest<EducationStatusViewModel>($"api/educationstatus/get?id={id}");
return educationstatus;
}
}
}

View File

@ -80,6 +80,24 @@ namespace UniversityProvider.Controllers
return View();
}
public IActionResult EducationStatuses(int page)
{
if (APIClient.User == null)
{
return Redirect("~/Home/Enter");
}
if (page == 0)
{
page = 1;
}
ViewBag.EducationStatuses = APIClient.GetRequest<List<EducationStatusViewModel>>
($"api/educationstatus/getmany?userId={APIClient.User.Id}&page={page}");
ViewBag.Page = page;
ViewBag.NumberOfPages = APIClient.GetRequest<int>
($"api/student/getnumberofpages?userId={APIClient.User.Id}");
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{

View File

@ -71,6 +71,15 @@ namespace UniversityProvider.Controllers
return students ?? new();
}
public List<StudentViewModel> GetAllByUserAndEducationStatus(int educationstatus)
{
if (APIClient.User == null)
{
return new();
}
List<StudentViewModel>? students = APIClient.GetRequest<List<StudentViewModel>>($"api/student/getallbyuserandeducationstatus?userId={APIClient.User.Id}&educationstatus={educationstatus}");
return students ?? new();
}
public StudentViewModel? Get(int id)
{

View File

@ -0,0 +1,58 @@
@using UniversityContracts.ViewModels
@{
ViewData["Title"] = "Статус обучения";
}
@{
<h4 class="fw-bold" id="vb-id">Назначение статуса обучения студенту</h4>
if (ViewBag.EducationStatusId == null)
{
<h3 class="display-4">Войдите в аккаунт</h3>
return;
}
<div class="row">
<div class="col-md-6">
<label id="educationStatusLabel" data-id="@ViewBag.EducationStatusId" for="educationStatusInput">Статус обучения:</label>
<input type="text" id="educationStatusInput" readonly value="" />
</div>
</div>
<div class="row">
<div class="col-md-6">
<label for="studentsSelect">Студенты:</label>
<select id="studentsSelect">
</select>
</div>
</div>
<button id="update-button" type="button" class="button-primary text-button">
Сохранить изменения
</button>
<div class="row">
<div class="col-md-12">
<h3>Итог:</h3>
<table>
<thead>
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody id="studentTable">
<tr id="emptyRow">
<td colspan="3">Выберите студента!</td>
</tr>
</tbody>
</table>
</div>
</div>
}
<script src="~/js/educationstatus/educationstatus-add-student.js" asp-append-version="true"></script>

View File

@ -0,0 +1,20 @@
@{
ViewData["Title"] = "Статус обучения";
}
<h4 class="fw-bold">Добавление статуса обучения</h4>
<div id="error-div-shell" class="error-div-shell mb-2">
<div>
<p id="error-p" class="error-p"></p>
</div>
</div>
<p class="mb-0">Название:</p>
<input type="text" id="name-input" name="name" class="form-control mb-3" />
<button id="create-button" type="button" class="button-primary text-button">
Создать
</button>
<script src="~/js/educationstatus/educationstatus-create.js" asp-append-version="true"></script>

View File

@ -0,0 +1,30 @@
@using UniversityContracts.ViewModels
@{
ViewData["Title"] = "Статус обучения";
}
@{
<h4 class="fw-bold" id="vb-id" data-id="@ViewBag.EducationStatus.Id">Изменение данных статуса обучения</h4>
if (ViewBag.EducationStatus == null)
{
<h3 class="display-4">Войдите в аккаунт</h3>
return;
}
<div id="error-div-shell" class="error-div-shell mb-2">
<div>
<p id="error-p" class="error-p"></p>
</div>
</div>
<p class="mb-0">Название:</p>
<input value="@ViewBag.EducationStatus.Name" type="text" id="name-input" name="name" class="form-control mb-3" />
<button id="update-button" type="button" class="button-primary text-button">
Сохранить изменения
</button>
}
<script src="~/js/educationstatus/educationstatus-update.js" asp-append-version="true"></script>

View File

@ -1,5 +1,71 @@
@*
For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@using UniversityContracts.ViewModels
@{
ViewData["Title"] = "Статусы обучения";
}
<div class="text-center">
<h1 class="display-4">Статусы обучения</h1>
</div>
<div class="text-center">
@{
if (ViewBag.EducationStatuses == null)
{
<h3 class="display-4">Войдите в аккаунт</h3>
return;
}
<div>
<a class="btn btn-secondary" asp-controller="EducationStatus" asp-action="Create">Добавить статус обучения</a>
</div>
<div class="d-flex mb-2 gap-1">
<div class="input-group" style="width: auto;">
<input id="page-input" type="number" min="1" value="@ViewBag.Page" max="@ViewBag.NumberOfPages" class="form-control" style="max-width: 5em">
<span class="input-group-text">/ @ViewBag.NumberOfPages</span>
</div>
<a href="/Home/EducationStatuses?page=@ViewBag.Page" id="go-button" class="button-primary text-button">
Перейти
</a>
</div>
<table class="table">
<thead>
<tr>
<th>
Название
</th>
<th>
Выбор студента
</th>
<th>
Изменить запись
</th>
<th>
Удалить запись
</th>
</tr>
</thead>
<tbody>
@foreach (var item in ViewBag.EducationStatuses)
{
<tr class="d-table-row">
<td>
@item.Name
</td>
<td>
<a id="add-student-button-@item.Id" class="btn btn-secondary" asp-controller="EducationStatus" asp-action="AddStudent" asp-route-id="@item.Id">Назначить статус для студента</a>
</td>
<td>
<a id="update-button-@item.Id" class="btn btn-secondary" asp-controller="EducationStatus" asp-action="Update" asp-route-id="@item.Id">Изменить</a>
</td>
<td>
<a id="remove-button-@item.Id" class="btn btn-secondary remove-btn" data-id="@item.Id">Удалить</a>
</td>
</tr>
}
</tbody>
</table>
}
</div>
<script src="~/js/educationstatus/educationstatuses.js" asp-append-version="true"></script>

View File

@ -0,0 +1,115 @@
const select = document.getElementById("studentsSelect");
const educationStatusId = document.getElementById("educationStatusLabel").dataset.id;
const educationStatusInput = document.getElementById("educationStatusInput");
const studentTable = document.getElementById("studentTable");
const updateBtn = document.getElementById("update-button");
var students = [];
var educationStatus = null;
window.addEventListener("load", () => {
$.ajax({
url: `/student/getallbyuserandeducationstatus?educationstatus=${educationStatusId}`,
type: "GET",
contentType: "json"
}).done((result) => {
students = result;
students.forEach((student) => {
createStudentOption(student);
});
});
$.ajax({
url: `/educationstatus/get?id=${educationStatusId}`,
type: 'GET',
contentType: 'json'
}).done((result) => {
console.log(result);
educationStatus = result;
fillEducationStatusInput(educationStatus);
});
});
updateBtn.addEventListener("click", () => {
if (select.selectedIndex === -1) {
return;
}
var student = students.find(x => x.id === parseInt(select.value));
student.educationStatusId = educationStatus.id;
$.ajax({
url: "/student/update",
type: "POST",
contentType: "application/json",
data: JSON.stringify(student)
}).done(() => {
window.location.href = "/Home/EducationStatuses";
});
})
const createStudentOption = (student) => {
const option = document.createElement("option");
option.value = student.id;
option.innerHTML = student.name + " " + student.surname + ", " + student.studentCard;
select.appendChild(option);
select.selectedIndex = -1;
}
const fillEducationStatusInput = (educationStatus) => {
educationStatusInput.value = educationStatus.name
}
select.addEventListener("change", () => {
studentTable.innerHTML = "";
const trName = document.createElement('tr');
const trSurname = document.createElement('tr');
const trStudentCard = document.createElement('tr');
const trEducationStatusName = document.createElement('tr');
var student = students.find(x => x.id === parseInt(select.value));
const tdNameField = document.createElement('td');
tdNameField.innerHTML = "Имя:";
const tdSurnameField = document.createElement('td');
tdSurnameField.innerHTML = "Фамилия:";
const tdStudentCardField = document.createElement('td');
tdStudentCardField.innerHTML = "Номер студ. билета:";
const tdEducationStatusNameField = document.createElement('td');
tdEducationStatusNameField.innerHTML = "Статус обучения:";
const tdNewEducationStatusName = document.createElement('td');
tdNewEducationStatusName.innerHTML = educationStatus.name;
const tdArrowEducationStatusName = document.createElement('td');
tdArrowEducationStatusName.innerHTML = "--->"
const tdName = document.createElement('td');
tdName.innerHTML = student.name;
const tdSurname = document.createElement('td');
tdSurname.innerHTML = student.surname;
const tdStudentCard = document.createElement('td');
tdStudentCard.innerHTML = student.studentCard;
const tdEducationStatusName = document.createElement('td');
tdEducationStatusName.innerHTML = student.educationStatusName;
trName.appendChild(tdNameField);
trName.appendChild(document.createElement('td'));
trName.appendChild(document.createElement('td'));
trName.appendChild(tdName);
trSurname.appendChild(tdSurnameField);
trSurname.appendChild(document.createElement('td'));
trSurname.appendChild(document.createElement('td'));
trSurname.appendChild(tdSurname);
trStudentCard.appendChild(tdStudentCardField);
trStudentCard.appendChild(document.createElement('td'));
trStudentCard.appendChild(document.createElement('td'));
trStudentCard.appendChild(tdStudentCard);
trEducationStatusName.appendChild(tdEducationStatusNameField);
trEducationStatusName.appendChild(tdNewEducationStatusName);
trEducationStatusName.appendChild(tdArrowEducationStatusName);
trEducationStatusName.appendChild(tdEducationStatusName);
studentTable.appendChild(trName);
studentTable.appendChild(trSurname);
studentTable.appendChild(trStudentCard);
studentTable.appendChild(trEducationStatusName);
})

View File

@ -0,0 +1,36 @@
const createBtn = document.getElementById("create-button");
const nameInput = document.getElementById("name-input");
createBtn.addEventListener("click", () => {
if (!correctData()) {
return;
}
if (!validate()) {
return;
}
});
const correctData = function () {
return true;
};
const validate = function () {
return true;
};
createBtn.addEventListener("click", () => {
let educationstatus = {
"Name": nameInput.value,
};
console.log(educationstatus)
$.ajax({
url: "/educationstatus/create",
type: "POST",
contentType: "application/json",
data: JSON.stringify(educationstatus)
}).done(() => {
window.location.href = "/Home/EducationStatuses";
});
});

View File

@ -0,0 +1,38 @@
const updateBtn = document.getElementById("update-button");
const nameInput = document.getElementById("name-input")
const studId = document.getElementById("vb-id").dataset.id
updateBtn.addEventListener("click", () => {
if (!correctData()) {
return;
}
if (!validate()) {
return;
}
});
const correctData = function () {
return true;
};
const validate = function () {
return true;
};
updateBtn.addEventListener("click", () => {
let educationstatus = {
"Id": parseInt(studId),
"Name": nameInput.value,
};
console.log(educationstatus)
$.ajax({
url: "/educationstatus/update",
type: "POST",
contentType: "application/json",
data: JSON.stringify(educationstatus)
}).done(() => {
window.location.href = "/Home/EducationStatuses";
});
});

View File

@ -0,0 +1,25 @@
const goToPageBtn = document.getElementById("go-button");
const pageInput = document.getElementById("page-input");
const removeButtons = document.querySelectorAll(".remove-btn");
removeButtons.forEach(function (button) {
button.addEventListener("click", function (event) {
var id = this.dataset.id;
var result = confirm("Вы уверены, что хотите удалить эту запись?");
if (result) {
$.ajax({
url: "/educationstatus/delete",
type: "POST",
data: { Id: id }
}).done(() => {
window.location.reload();
});
}
});
});
pageInput.addEventListener("input", () => {
const pageNumber = parseInt(pageInput.value);
goToPageBtn.href = `/Home/Students?page=${pageNumber}`;
});

View File

@ -32,9 +32,9 @@ createBtn.addEventListener("click", () => {
};
console.log(student)
$.ajax({
url: `/student/create`,
type: 'POST',
contentType: 'application/json',
url: "/student/create",
type: "POST",
contentType: "application/json",
data: JSON.stringify(student)
}).done(() => {
window.location.href = "/Home/Students";

View File

@ -12,7 +12,6 @@ updateBtn.addEventListener("click", () => {
if (!validate()) {
return;
}
form.submit();
});
const correctData = function () {
@ -35,9 +34,9 @@ updateBtn.addEventListener("click", () => {
};
console.log(student)
$.ajax({
url: `/student/update`,
type: 'POST',
contentType: 'application/json',
url: "/student/update",
type: "POST",
contentType: "application/json",
data: JSON.stringify(student)
}).done(() => {
window.location.href = "/Home/Students";

View File

@ -1,16 +1,16 @@
const goToPageBtn = document.getElementById("go-button");
const pageInput = document.getElementById("page-input");
const removeButtons = document.querySelectorAll('.remove-btn');
const removeButtons = document.querySelectorAll(".remove-btn");
removeButtons.forEach(function (button) {
button.addEventListener('click', function (event) {
button.addEventListener("click", function (event) {
var id = this.dataset.id;
var result = confirm("Вы уверены, что хотите удалить эту запись?");
if (result) {
$.ajax({
url: `/student/delete`,
type: 'POST',
url: "/student/delete",
type: "POST",
data: { Id: id }
}).done(() => {
window.location.reload();

View File

@ -1,12 +1,111 @@
using Microsoft.AspNetCore.Mvc;
using UniversityContracts.BindingModels;
using UniversityContracts.BusinessLogicContracts;
using UniversityContracts.SearchModels;
using UniversityContracts.ViewModels;
namespace UniversityRestAPI.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class EducationStatusController : Controller
{
public IActionResult Index()
private readonly IEducationStatusLogic _educationStatusLogic;
public EducationStatusController(IEducationStatusLogic educationStatusLogic)
{
return View();
_educationStatusLogic = educationStatusLogic;
}
[HttpGet]
public EducationStatusViewModel? Get(int id)
{
try
{
return _educationStatusLogic.ReadElement(new EducationStatusSearchModel { Id = id });
}
catch (Exception ex)
{
throw;
}
}
[HttpGet]
public List<EducationStatusViewModel>? GetAllByUser(int userId)
{
try
{
return _educationStatusLogic.ReadList(null);
}
catch (Exception ex)
{
throw;
}
}
[HttpGet]
public List<EducationStatusViewModel>? GetMany(int userId, int page)
{
try
{
return _educationStatusLogic.ReadList(new EducationStatusSearchModel { UserId = userId, PageNumber = page, PageSize = 10 });
}
catch (Exception ex)
{
throw;
}
}
[HttpGet]
public int GetNumberOfPages(int userId)
{
try
{
return _educationStatusLogic.GetNumberOfPages(userId);
}
catch (Exception ex)
{
throw;
}
}
[HttpPost]
public void Create(EducationStatusBindingModel model)
{
try
{
_educationStatusLogic.Create(model);
}
catch (Exception ex)
{
throw;
}
}
[HttpPost]
public void Update(EducationStatusBindingModel model)
{
try
{
_educationStatusLogic.Update(model);
}
catch (Exception ex)
{
throw;
}
}
[HttpPost]
public void Delete(EducationStatusBindingModel model)
{
try
{
_educationStatusLogic.Delete(new() { Id = model.Id });
}
catch (Exception ex)
{
throw;
}
}
}
}

View File

@ -35,7 +35,20 @@ namespace UniversityRestAPI.Controllers
{
try
{
return _studentLogic.ReadList(null);
return _studentLogic.ReadList(new StudentSearchModel { UserId = userId });
}
catch (Exception ex)
{
throw;
}
}
[HttpGet]
public List<StudentViewModel>? GetAllByUserAndEducationStatus(int userId, int educationstatus)
{
try
{
return _studentLogic.ReadList(new StudentSearchModel { UserId = userId, EducationStatusId = educationstatus });
}
catch (Exception ex)
{