我對 Asp.net 核心 MVC 相當陌生,并且花了幾天時間研究這個問題,但我找不到我的錯誤。
我只是試圖將資料從 ViewModel 傳遞到視圖中的表,但 ViewModel 沒有填充資料。
這是我的代碼:
我目前正在使用的模型(其他模型在不同的列中看起來相同):
using System;
using System.Collections.Generic;
namespace Seating.Models
{
public partial class Dth
{
public int Id { get; set; }
public DateTime TimeEntered { get; set; }
public DateTime? TimeCleared { get; set; }
public bool? EmpSent { get; set; }
public int EmployeeId { get; set; }
public int EmpPosition { get; set; }
public int? RlfPosition { get; set; }
public virtual Position EmpPositionNavigation { get; set; }
public virtual Employee Employee { get; set; }
public virtual Position RlfPositionNavigation { get; set; }
}
}
虛擬機:
using Seating.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Seating.ViewModels
{
public class ListsVM
{
public IEnumerable<Dth> Dths { get; set; }
public IEnumerable<Break> Breaks { get; set; }
public IEnumerable<Lunch> Lunches { get; set; }
public IEnumerable<Employee> Employees { get; set; }
public IEnumerable<Position> Positions { get; set; }
}
}
控制器:
using Seating.Models;
using Seating.ViewModels;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
namespace Seating.Controllers
{
public class HomeController : Controller
{
private readonly db_a7e17a_seatingContext _context = new db_a7e17a_seatingContext();
public HomeController(db_a7e17a_seatingContext context)
{
_context = context;
}
public ActionResult Index()
{
var tables = new ListsVM
{
Employees = _context.Employees.ToList(),
Dths = _context.Dths.Where(n => n.TimeCleared == null).ToList(),
Breaks = _context.Breaks.Where(n => n.TimeCleared == null).ToList(),
Lunches = _context.Lunches.Where(n => n.TimeCleared == null).ToList(),
Positions = _context.Positions.ToList()
};
return View(tables);
}
并查看:
@model IEnumerable<Seating.ViewModels.ListsVM>
@{
ViewData["Title"] = "Home Page";
}
<div class="card" style="width: 18rem;">
<div class="card-header text-center">
DTH
</div>
<table class="table table-sm">
<tbody>
@foreach (var item in Model.Dths)
{
<tr>
@item.EmployeeId
</tr>
}
</tbody>
</table>
</div>
我收到一條錯誤訊息,說“IEnumerable”不包含“Dths”的定義,可以找到“IEnumerable”型別的第一個引數。
我嘗試在 VM 中將“IEnumerable”更改為“List”。我已經閱讀了許多關于 stackoverflow 的解決方案。我已經學習了一些教程,這些教程向我展示了如何進行設定。據我所知,我正在嚴格按照教程代碼進行操作,甚至認為我顯然不在某個地方。
我將視圖中的模型參考更改為 @model IEnumerable<Seating.Models.Dth> 而不是 VM。這完美無缺。所以我假設我對虛擬機做錯了,因為它可以直接參考模型而無需通過虛擬機。
對我做錯了什么有任何想法嗎?
uj5u.com熱心網友回復:
您正在創建一個ListsVM包含不同型別物體串列的型別物件。這個物件通過 傳遞給視圖View(tables)。但是在視圖中,您將模型宣告為物件集合ListsVM:@model IEnumerable<Seating.ViewModels.ListsVM>
您是否嘗試將模型宣告更改為@model Seating.ViewModels.ListsVM?
如果將視圖模型宣告為@model Seating.ViewModels.ListsVM,Model.Dths則將參考正確的集合,并且@foreach (var item in Model.Dths)將正確列舉此集合。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/407926.html
標籤:
上一篇:影像未保存在資料庫django中
