From 9da8a0fd79bba5917943caa26660d80dea81c10b Mon Sep 17 00:00:00 2001 From: GokaPek Date: Tue, 28 May 2024 19:17:05 +0400 Subject: [PATCH] =?UTF-8?q?=D0=9C=D0=BD=D0=BE=D0=B3=D0=B8=D0=B5=20=D0=BA?= =?UTF-8?q?=D0=BE=20=D0=BC=D0=BD=D0=BE=D0=B3=D0=B8=D0=BC=20=D0=B5=D0=B3?= =?UTF-8?q?=D0=BE=D1=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../UniversityClientApp/APIStorekeeper.cs | 76 +++++++++++++++++++ .../Controllers/HomeController.cs | 53 ++----------- .../ViewModels/DisciplineViewModel.cs | 8 ++ 3 files changed, 92 insertions(+), 45 deletions(-) diff --git a/University/UniversityClientApp/APIStorekeeper.cs b/University/UniversityClientApp/APIStorekeeper.cs index 69a5f82..5ab6a4d 100644 --- a/University/UniversityClientApp/APIStorekeeper.cs +++ b/University/UniversityClientApp/APIStorekeeper.cs @@ -4,6 +4,9 @@ using System.Net.Http.Headers; using Newtonsoft.Json; using System.Text; using UniversityContracts.ViewModels; +using Azure.Core; +using UniversityDataModels.Models; +using UniversityDatabaseImplement.Models; namespace UniversityClientAppStorekeeper { @@ -44,5 +47,78 @@ namespace UniversityClientAppStorekeeper throw new Exception(result); } } + public static async Task GetRequestDisciplineAsync(string requestUrl) + { + var response = await _client.GetAsync(requestUrl); + var result = await response.Content.ReadAsStringAsync(); + if (response.IsSuccessStatusCode) + { + var settings = new JsonSerializerSettings + { + Converters = new List { new StudentConverter()} + }; + + return JsonConvert.DeserializeObject(result, settings); + } + else + { + throw new Exception(result); + } + } } + + + + public class StudentConverter : JsonConverter + { + public override bool CanConvert(Type objectType) + { + return objectType == typeof(IStudentModel); + //return true; + } + + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + if (reader.TokenType == JsonToken.Null) + return null; + + if (existingValue is Student student) + return student; + + var student1 = new Student(); + serializer.Populate(reader, student1); + return student1; + } + + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + if (value == null) + { + writer.WriteNull(); + return; + } + + var student = (Student)value; + serializer.Serialize(writer, student); + } + } + + public class DisciplineConverter : JsonConverter + { + public override bool CanConvert(Type objectType) + { + return objectType == typeof(IDisciplineModel); + //return true; + } + + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + return serializer.Deserialize(reader); + } + + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + serializer.Serialize(writer, value); + } + } } diff --git a/University/UniversityClientApp/Controllers/HomeController.cs b/University/UniversityClientApp/Controllers/HomeController.cs index 017c641..b830eeb 100644 --- a/University/UniversityClientApp/Controllers/HomeController.cs +++ b/University/UniversityClientApp/Controllers/HomeController.cs @@ -79,15 +79,21 @@ namespace UniversityClientApp.Controllers } [HttpGet] - public IActionResult Disciplines() + public async Task Disciplines() { if (APIStorekeeper.Client == null) { return Redirect("~/Home/Enter"); } + ViewBag.Teachers = APIStorekeeper.GetRequest>($"api/teacher/getteachers?userId={APIStorekeeper.Client.Id}"); ViewBag.Students = APIStorekeeper.GetRequest>($"api/student/getstudents?userId={APIStorekeeper.Client.Id}"); - return View(APIStorekeeper.GetRequest>($"api/discipline/getdisciplines?teacherId={0}")); + + // Ожидаем завершения асинхронной операции + var disciplines = await APIStorekeeper.GetRequestDisciplineAsync>($"api/discipline/getdisciplines?teacherId={0}"); + + // Теперь мы можем передать результат в представление + return View(disciplines); } [HttpPost] public void Disciplines(string name, string description, DateOnly date, int teacher, List studentIds) @@ -112,49 +118,6 @@ namespace UniversityClientApp.Controllers Response.Redirect("Disciplines"); } - /*public IActionResult Disciplines(string name, string description, DateOnly date, int teacher, List studentIds) - { - if (APIStorekeeper.Client == null) - { - return RedirectToAction("Enter", "Home"); - } - - // Предполагаем, что у вас есть доступ к контексту базы данных UniversityDatabase - using (var context = new UniversityDatabase()) - { - // Создаем словарь для хранения студентов - var studentDisciplines = new Dictionary(); - - // Итерируем по списку идентификаторов студентов - foreach (var studentId in studentIds) - { - // Получаем студента из базы данных или создаем новый экземпляр Student - // Вам нужно будет заполнить необходимые свойства, такие как UserId, PlanOfStudyId, Name и PhoneNumber - var student = context.Students.Find(studentId); - - // Добавляем студента в словарь - studentDisciplines.Add(studentId, student); - } - - var disciplineModel = new DisciplineBindingModel - { - UserId = APIStorekeeper.Client.Id, - Name = name, - Description = description, - Date = date, - TeacherId = teacher, - StudentDisciplines = studentDisciplines - }; - - APIStorekeeper.PostRequest("api/discipline/creatediscipline", disciplineModel); - - return RedirectToAction("Disciplines"); - } - }*/ - - - - diff --git a/University/UniversityContracts/ViewModels/DisciplineViewModel.cs b/University/UniversityContracts/ViewModels/DisciplineViewModel.cs index 074f613..db3ebbd 100644 --- a/University/UniversityContracts/ViewModels/DisciplineViewModel.cs +++ b/University/UniversityContracts/ViewModels/DisciplineViewModel.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; +using System.Text.Json.Serialization; using System.Threading.Tasks; using UniversityDataModels.Models; @@ -25,5 +26,12 @@ namespace UniversityContracts.ViewModels get; set; } = new(); + + public DisciplineViewModel() { } + + [JsonConstructor] + public DisciplineViewModel(Dictionary disciplineStudents) { + this.StudentDisciplines = disciplineStudents.ToDictionary(x => x.Key, x => x.Value as IStudentModel); + } } }