错误:
InvalidOperationException:传递给ViewDataDictionary的模型项的类型为'Test.Models.Ticket []',但是此ViewDataDictionary实例需要类型为'Test.Models.Ticket'的模型项。
你好,
盯着几天的错误并进行了一些研究之后,我确定对MVC的了解不足以解决此问题。我很了解,知道我的控制器正在尝试将数组传递给视图,但是视图没有在寻找array(?)。下面是代码:
控制器:
//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上的一篇精彩文章,但是尽管我认为这对我了解正在发生的事情在很多方面都给了我很大的帮助,但我仍然发现该错误难以解决。
答案 0 :(得分:1)
问题在于,视图正在使用的布局期望使用Ticket
模型,并且您正在向其传递Ticket[]
(注意,使用return View(model)
时会隐式完成)。
通常,由于布局是通过多个视图使用的,因此布局不会声明@model
。从版式中删除@model
将解决您的问题。