gpt4 book ai didi

c# - 传递给 ViewDataDictionary 的模型项是 X[] 类型,但是这个 ViewDataDictionary 实例需要一个 X 类型的模型项

转载 作者:行者123 更新时间:2023-11-30 17:29:18 25 4
gpt4 key购买 nike

<分区>

错误:

InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'Test.Models.Ticket[]', but this ViewDataDictionary instance requires a model item of type 'Test.Models.Ticket'.

你好,
在盯着一个错误几天并做了一些研究之后,我确定我对 MVC 的了解还不足以解决这个问题。我的理解足以知道我的 Controller 正在尝试将数组传递给 View ,但 View 不是在寻找数组(?)。下面是代码:

Controller :

//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);
}

View :(文件名为“Index.cshtml”,位于“Views”文件夹内的“Ticket”文件夹下)

@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>

部分 View “_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 的精彩帖子,但尽管我认为这在我理解正在发生的事情的许多方面对我帮助很大,但我仍然发现该错误难以解决。

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com