Просмотр в приложении C# ASP.NET Core MVC не получает данныеC#

Место общения программистов C#
Ответить
Anonymous
 Просмотр в приложении C# ASP.NET Core MVC не получает данные

Сообщение Anonymous »

Я создаю CMS, в которой показываю информацию из базы данных. Это школьная база данных. У меня есть одна страница (Вид - Список), на которой есть список учителей. Когда пользователь нажимает на одного учителя, он перенаправляется на другую страницу (просмотр-показать), на которой должна быть информация об этом конкретном учителе. Проблема в том, что страница «Список» получает данные и отображает их, но страница «Показать» не получает никаких данных и не выдает никаких ошибок. Просто данные не отображаются.
Это мой код — List.cshtml:
@model IEnumerable

This page shows the list of all the teachers.

@foreach(Cumulative.Models.Teacher CurrentTeacher in Model)
{
@CurrentTeacher.TeacherFName @CurrentTeacher.TeacherLName
}

Show.cshtml:
@model Cumulative.Models.Teacher
@Model.TeacherFName @Model.TeacherLName

TeacherPageController:
using Microsoft.AspNetCore.Mvc;
using Cumulative.Models;
using Cumulative.Controllers;
using Google.Protobuf.WellKnownTypes;

namespace Cumulative.Controllers
{
public class TeacherPageController : Controller
{
private readonly TeacherAPIController _api;

public TeacherPageController(TeacherAPIController api)
{
_api = api;
}

// TeacherPage/List -> A webpage that shows all teachers in the database
public IActionResult List()
{
// creating a variable for the list of teachers
List Teachers = _api.ListTeachers();

// direct us to the /Views/TeacherPage/List.cshtml
return View(Teachers);
}

// GET : TeacherPage/Show/{id} -> A webpage that shows a particular teacher in the database matching the given id
[HttpGet]
public IActionResult Show(int TeacherId)
{
// Creating a Teacher instance for the teacher information received upon inserting the id
Teacher SelectedTeacher = _api.GiveTeacherInfo(TeacherId);

return View(SelectedTeacher);
}
}
}

TeacherAPIController:
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Cumulative.Models;
using System;
using MySql.Data.MySqlClient;

namespace Cumulative.Controllers
{
[Route("api/Teacher")]
[ApiController]
public class TeacherAPIController : ControllerBase
{
private readonly SchoolDbContext _context;
// dependency injection of database context
public TeacherAPIController(SchoolDbContext context)
{
_context = context;
}

///
/// Returns information about all the teachers
///
///
/// GET api/teacher/GiveTeachersList -> ["","","","",""]
///
///
/// A list of the teachers
///
///
[HttpGet]
[Route(template:"ListTeachers")]
public List ListTeachers()
{
// Create a list of instances of Teachers
List Teachers = new List();

// 'using' will close the connection after the code executes
using (MySqlConnection Connection = _context.AccessDatabase())
{
Connection.Open();
// Establish a new command (query) for our database
MySqlCommand Command = Connection.CreateCommand();

//SQL query
Command.CommandText = "SELECT * FROM teachers";

// Gather Result Set of Query into a variable
using (MySqlDataReader ResultSet = Command.ExecuteReader())
{
//Loop Through Each Row of the Result Set
while (ResultSet.Read())
{
int Id = Convert.ToInt32(ResultSet["teacherid"]);
string LastName = ResultSet["teacherlname"].ToString();
string EmployeeNumber = ResultSet["employeenumber"].ToString();
DateTime HireDate = Convert.ToDateTime(ResultSet["hiredate"]);
Decimal Salary = Convert.ToDecimal(ResultSet["salary"]);

// Add the Teacher Data to the Teachers

Teacher CurrentTeacher = new Teacher()
{
TeacherId = Id,
TeacherFName = ResultSet["teacherfname"].ToString(),
TeacherLName = LastName,
EmployeeNumber = EmployeeNumber,
HireDate = HireDate,
Salary = Salary
};

Teachers.Add(CurrentTeacher);
}
}
}

return Teachers;
}

///
/// Receives a teacher id and returns the associated teacher information
///
///
The primary key of the teachers table.
///
/// GET api/teacher/GiveTeacherInfo/5 -> {"":"","":"","":""}
///
///
/// All the information about one teacher
///

[HttpGet]
[Route(template:"GiveTeacherInfo/{TeacherId}")]
public Teacher GiveTeacherInfo(int TeacherId)
{
Teacher SelectedTeacher = new Teacher();

// 'using' will close the connection after the code executes
using (MySqlConnection Connection = _context.AccessDatabase())
{
Connection.Open();
// Establish a new command (query) for our database
MySqlCommand Command = Connection.CreateCommand();

// SQL query
Command.CommandText = $"SELECT * FROM teachers WHERE teacherid = {TeacherId}";

// Gather Result Set of Query into the Teacher
using (MySqlDataReader ResultSet = Command.ExecuteReader())
{
//Loop Through Each Row of the Result Set
while (ResultSet.Read())
{
SelectedTeacher.TeacherId = Convert.ToInt32(ResultSet["teacherid"]);
SelectedTeacher.TeacherFName = ResultSet["teacherfname"].ToString();
SelectedTeacher.TeacherLName = ResultSet["teacherlname"].ToString();
SelectedTeacher.EmployeeNumber = ResultSet["employeenumber"].ToString();
SelectedTeacher.HireDate = Convert.ToDateTime(ResultSet["hiredate"]);
SelectedTeacher.Salary = Convert.ToDecimal(ResultSet["salary"]);

}
}
}

return SelectedTeacher;
}
}
}

Teacher класс:
namespace Cumulative.Models
{
public class Teacher
{
public int TeacherId { get; set; }

public string TeacherFName { get; set; }
public string TeacherLName { get; set; }
public string EmployeeNumber { get; set; }

public DateTime HireDate { get; set; }

public Decimal Salary { get; set; }
}
}


Подробнее здесь: https://stackoverflow.com/questions/792 ... tting-data
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»