【发布时间】:2018-12-25 14:09:16
【问题描述】:
错误:
InvalidOperationException:传递到 ViewDataDictionary 的模型项属于“Test.Models.Ticket[]”类型,但此 ViewDataDictionary 实例需要“Test.Models.Ticket”类型的模型项。
你好,
盯着一个错误看了几天,做了一些研究,我确定我对MVC的了解不够,无法解决这个问题。我足够了解我的控制器正在尝试将数组传递给视图,但视图不是在寻找数组(?)。下面是代码:
控制器:
//this is supposed to take the last five "tickets" created from a database
[Route("Ticket")]
public IActionResult Index(int page = 0)
{
var model = _db.Tickets.OrderByDescending(x => x.Time).Take(5).ToArray();
return View(model);
}
视图:(文件在“视图”文件夹内的“票证”文件夹下名为“Index.cshtml”)
@model IEnumerable<Test.Models.Ticket>
@{
Layout = "_Layout";
}
<p>Below is supposed to display the latest 5 "tickets" from a database.</p>
<div class="ticket-create">
@foreach (var ticket in Model)
{
@Html.Partial("_Ticket", ticket)
}
</div>
部分视图“_Ticket”:
@model Test.Models.Ticket
<article class="ticket-create">
<h1>@Html.ActionLink(Model.Type, "Create", "Ticket", new { year = Model.Time.Year, month = Model.Time.Month, day = Model.Time.Day, time = Model.Time.TimeOfDay, key = Model.Key })</h1>
<div class="type">
Created on <span>@Model.Time</span> by <span>@Model.Name</span>
</div>
<div class="desc">
@Model.Desc
</div>
<div class="clearance">
@Model.Clearance
</div>
</article>
模型“票”:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace Test.Models
{
public class Ticket
{
public long Id { get; set; }
private string _key;
public string Key
{
get
{
if(_key == null)
{
_key = Regex.Replace(Name.ToLower(), "[^a-z0-9]", "-");
}
return _key;
}
set { _key = value; }
}
[Required]
[DataType(DataType.Text)]
public string Type { get; set; }
[Required]
[DataType(DataType.Text)]
public string Name { get; set; }
[StringLength(300, MinimumLength = 5, ErrorMessage = "The description must be between 5 and 300 characters long.")]
[DataType(DataType.MultilineText)]
public string Desc { get; set; }
[DataType(DataType.DateTime)]
public DateTime Time { get; set; }
[Required]
[DataType(DataType.Text)]
public string Clearance { get; set; }
[DataType(DataType.Text)]
public string Author { get; set; }
}
}
_Layout.cshtml 声明以下模型:“@model Test.Models.Ticket”
我阅读了位于 here 的精彩帖子,虽然我认为这在我理解正在发生的事情的许多方面帮助了我很多,但我仍然发现这个错误很难解决。
【问题讨论】:
-
你能确认View下的代码是在一个名为Index.cshtml的文件上吗?
-
是的,我可以确认。抱歉,如果这看起来有点令人困惑,我应该坚持使用更常识的标题。代码位于“Views”文件夹下的“Ticket”文件夹中的“Index.cshtml”文件中。
-
_Layout.cshtml 是否声明了@model 类型?
-
_Layout.cshtml 声明了以下模型:“@model Test.Models.Ticket”
-
布局不应声明模型,因为每个视图都必须使用它。
标签: c# asp.net-mvc