我最近开始在 ASP.NET 中编写我的第一个项目(名称 - 查找门票(火车/飞机)的网站),我遇到了一个问题,当我想以列表的形式发送数据时,它就停止工作了😭,但是如果我通过了,那么对象就全部转移了,没有问题
附注我会在 GitHub 上留下链接,希望有人能帮助我解决问题😔 链接Github
这里这个方法不起作用(
public async Task<IActionResult> FindTickets(Tickets tickets)
{
var availableTickets = await _tickets.GetAll();
var find = availableTickets.Where(t => t.StartAirport == tickets.StartAirport && t.EndAirport == tickets.EndAirport);
return View(find);
}
这才是应该转移的地方(别看这么吓人,都是为了测试,仅此而已)
@model List<Tickets>
@{
ViewData["Title"] = "Tickets";
}
@foreach (var ticket in Model)
{
<h1>@ticket.Id</h1>
<h1>@ticket.StartAirport</h1>
<h1>@ticket.EndAirport</h1>
<h1>@ticket.DepartureDate</h1>
<h1>@ticket.ArrivalDate</h1>
<h1>@ticket.ClassSeat</h1>
}
全班
using AviaTikets.Interfaces;
using AviaTikets.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using System.Diagnostics;
using System.Net.Sockets;
namespace AviaTikets.Controllers
{
public class AirTicketsController : Controller
{
private readonly ILogger<AirTicketsController> _logger;
private readonly ITickets _tickets;
public AirTicketsController(ILogger<AirTicketsController> logger, ITickets tickets)
{
_logger = logger;
_tickets = tickets;
}
public async Task<IActionResult> FindTickets(Tickets tickets)
{
var availableTickets = await _tickets.GetAll();
var find = availableTickets.Where(t => t.StartAirport == tickets.StartAirport && t.EndAirport == tickets.EndAirport);
return View(find);
}
public IActionResult Index()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
public async Task<IActionResult> GetAll()
{
var ticketsList = await _tickets.GetAll();
return Ok(ticketsList);
}
public async Task<IActionResult> GetTiket(int id)
{
var ticketsId = await _tickets.GetTiketsById(id);
return Ok(ticketsId);
}
[HttpPost]
public async Task<IActionResult> Set(Tickets tickets)
{
_tickets.Add(tickets);
return Ok(tickets);
}
public async Task<IActionResult> Delete(int id)
{
var tikets = await _tickets.GetTiketsById(id);
if (tikets is null)
{
return Ok("Він пустий (");
}
_tickets.Delete(tikets);
return Ok();
}
[HttpPost]
public async Task<IActionResult> Update(int id, Tickets ticketsProp)
{
var tikets = await _tickets.GetTiketsById(id);
if (tikets is null)
{
return Ok("Не знайдено (");
}
var newTikes = new Tickets
{
StartAirport = ticketsProp.StartAirport,
EndAirport = ticketsProp.EndAirport,
DepartureDate = ticketsProp.DepartureDate,
ArrivalDate = ticketsProp.ArrivalDate,
ClassSeat = ticketsProp.ClassSeat,
};
_tickets.Update(newTikes);
return Ok();
}
}
}
您实际上并未将
List<Tickets>
传递到您的页面。您正在传递一个从 IEnumerable
调用返回的 Where
。
试试这个:
return View(find.ToList());
或者这个:
@model IEnumerable<Tickets>